c++ - move 运算符=和复制运算符=之间的区别

标签 c++ copy move-semantics assignment-operator

考虑这段代码:

#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/

相关文章:

c++ - 如何在 C++ 中使用 Boost 库的 Rtree?

ruby-on-rails-3 - Rails 克隆复制或复制

python - 全局列表不断变化,尽管复制

c++ - 警告 : defaulted move assignment operator of X will move assign virtual base class Y multiple times

c++ - 没有 if-else 语句的一维卷积(非 FFT)?

c++ - 如何防止可变参数构造函数优于复制构造函数?

linux - 如何将文件复制到多个子目录linux

C++ move 语义 : appending the matrix referenced by a unique_ptr to a vector

rust - Rust 如何 move 不可复制的堆栈变量?

c++ - 自动修复 C++ 代码库中的文件名大小写?