考虑这段代码:
#include <iostream>
using namespace std;
class A
{
int x;
public:
A () {x=5;}
A (const A & a) {x=a.x;}
A (A && a) {x=move(a.x);}
A & operator= (const A & a) {x=a.x;}
A & operator = (A && a) {x=move(a.x);}
void func () {A a; *this=move(a);}
};
int main () {A a; a.func();}
A::func()
创建一个 A 对象,然后 *this
使用 move operator=
赋值给 A。在该赋值中 move operator=
和复制 operator=
之间有什么区别?
当我要复制的对象将在函数结束时过期时,显式使用 move 赋值运算符(使用 move
)而不是复制运算符是否更有效?
如果我使用 move 赋值运算符,赋值后 a
是否仍然存在?
最佳答案
您的问题“使用 move 赋值是否更有效”有点倒退。当它更有效率时,您可以使用 move 分配。
如果您认为您可以实现比复制赋值“更好”的 move 赋值,您可以添加另一个运算符。
如果像在您的示例中一样,您发现很难优化复制 int
的操作,那么您不必为 move 而烦恼。
关于c++ - move 运算符=和复制运算符=之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32543215/