c++17 - 为什么我不能从移动复制ctor调用移动分配?
问题描述
如果我可以从移动 ctor 调用移动分配操作,有时它看起来像节省时间。但是当我尝试时,它会直接将我带到常规作业:
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass() { }
MyClass(const MyClass& other) { /* do some stuff */ }
MyClass(MyClass&& other); //move ctor
const MyClass& operator= (const MyClass& other);
const MyClass& operator= (MyClass&& other); //move =
};
MyClass::MyClass(MyClass&& other) //move ctor
{
cout << "Calling move ctor\n";
*this = other; //<<--THIS IS THE PROBLEM
}
const MyClass& MyClass::operator= (MyClass&& other) //move =
{
cout << "Calling move =\n";
return *this;
}
const MyClass& MyClass::operator= (const MyClass& other)
{
cout << "Calling standard =\n";
if (this == &other) return *this;
return *this;
}
MyClass makeVectorToTestMoveCtor() { MyClass V; return V; }
int main ()
{
MyClass V = makeVectorToTestMoveCtor();
return 0;
}
我可以用 std::move 强制它:
cout << "Calling move ctor\n";
*this = std::move(other);
...但如果这不是一个坏主意,我肯定不需要强迫它吗?我应该在这里做什么?
解决方案
施工是更基础的操作。您必须先有一个构造对象,然后才能分配给它或从它分配。用构造的方式写你的作业,而不是相反。
推荐阅读
- javascript - 用于验证和检索字符串的 Javascript 正则表达式不起作用
- python - 如何使用 Flask 渲染 VueJS 前端?
- kendo-ui - 可以为 Kendo 网格中的 columns.filterable.multi 设置自定义文本吗
- javascript - 设置输入字段的值,基于点击一组href链接
- kubernetes - 无法将新节点加入现有集群:[发现] 请求集群信息失败,将重试:[未授权]
- mongodb - Mongorestore 花时间恢复收藏
- javascript - RxJs combineLatest 似乎模拟了一个额外的更新
- apache-camel - 没有反馈的骆驼文件消费者错误
- python - Jupyter Notebook 在执行期间更改变量
- c - Strtok 为字符串的最后一个标记返回 NULL