我是 C++ 11/17 的新手,试图了解右值引用移动的工作原理。在下面的代码中,“修改的复制构造函数”和“移动构造函数”之间有什么区别?我让他们做同样的事情,但只有不同的原型。如果我在注释中添加“移动构造函数”,那么“修改的复制构造函数”也会执行相同的操作。
我的观点是为什么我们需要“移动构造函数”,现在的 C++17 与旧版本的 C++98 有什么不同?我之前只能通过不同地实现“复制构造函数”来完成同样的事情,并避免它过去所做的所有深度复制。我缺少什么?我不明白的是?
#include <iostream>
class A {
public:
int* arr, size;
bool flag;
// parameterized constructor
A(int len) {
size = len;
arr = new int[size];
flag = false;
}
// modified copy constructor
A(A& temp) {
arr = temp.arr;
size = temp.size;
flag = temp.flag;
temp.arr = NULL;
}
// move constructor
A(A&& temp) {
arr = temp.arr;
size = temp.size;
flag = temp.flag;
temp.arr = NULL;
std::cout << " A(A&& temp)" …Run Code Online (Sandbox Code Playgroud)