【发布时间】:2019-11-09 21:18:50
【问题描述】:
如果我可以从移动 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);
...但如果这不是一个坏主意,我肯定不需要强迫它吗?我应该在这里做什么?
【问题讨论】:
标签: c++17 move-semantics