c++ - 在一个可简单复制的结构中,是否应该实现移动语义?
问题描述
我有这样一个结构:
template <class T> struct Dimensions
{
T horizontal{}, vertical{};
Dimensions() = default;
Dimensions(const T& horizontal, const T& vertical)
: horizontal(horizontal), vertical(vertical) {}
Dimensions(const Dimensions& other) = default;
Dimensions& operator=(const Dimensions& other) = default;
Dimensions(Dimensions&& other) = default; // ?
Dimensions& operator=(Dimensions&& other) = default; // ?
~Dimensions() = default;
// ... + - * / += -= *= areNull() ...
}
我实例化喜欢Dimensions<int>
or Dimensions<double>
。由于它是可简单复制的,这里最好的策略是什么,生成移动构造函数和移动赋值运算符,= default
或者避免隐式运算符= delete
?
解决方案
生成移动构造函数和移动赋值运算符作为
= default
或避免隐式运算符= delete
?
前者,除非您希望任何尝试std::move
您的类型的代码编译失败。例如
template <typename T>
void foo()
{
T a;
T b = std::move(a);
}
struct X
{
X() = default;
X(X&&) = delete;
};
int main() { foo<X>(); }
推荐阅读
- html - 为什么在 VueJS 中做幻灯片效果时需要将图像设置为绝对位置?
- javascript - 使用 JavaScript 在文本文件中保存 URL 路径
- javascript - 如何在 grpc-js 服务器中添加多个服务?
- hadoop - AnalysisException:在运行 Hive 插入查询时,exprs 的返回类型“BOOLEAN”和“STRING”不兼容
- python - 如何在 Databricks 中从 Microsoft Onedrive 下载文档?
- sql - PostgreSQL 查询当前周趋势
- mysql - 为什么我得到错误的结果集mysql?
- r - 如何双重填充具有两个特征的 geom_bar
- python-3.x - 使用 Selenium 和 Chrome 下载 .xml 或任何文件(不能在浏览器中打开)
- python - 在python中加载具有多个内部类的类对象