我正在阅读 Bjarne Stroustrup 所著的《C++ 之旅》第二版的第 5 章。他使用 Vector 的示例实现来传达他的想法,并进入移动构造函数并显示代码,但表示移动赋值类似,但没有显示代码。
移动构造函数不接受 const 参数:毕竟,移动构造函数应该从其参数中删除值。移动分配的定义类似。
class Vector { public: Vector(int sz); // constructor Vector(const Vector &v); // copy constructor Vector &operator=(const Vector &v); // copy assignment Vector(Vector &&v); // move constructor Vector &operator=(Vector &&v); // move assignment ~Vector(); // destructor private: double *elem; int sz; }; Vector::Vector(int sz) : elem{new double[sz]}, sz{sz} { } Vector::Vector(const Vector &v) : elem{new double[v.sz]}, sz{v.sz} // copy constructor { for (int i = 0; i != sz; ++i) { elem[i] = v.elem[i]; } } Vector &Vector::operator=(const Vector &v) // copy assignment { double *p = new double[v.sz]; for (int i = 0; i != v.sz; ++i) { p[i] = v.elem[i]; } delete[] elem; // delete all elements elem = p; sz = v.sz; return *this; } Vector::~Vector() { delete[] elem; } Vector::Vector(Vector &&v) // move constructor : elem{v.elem}, sz{v.sz} { v.elem = nullptr; v.sz = 0; }
这是正确的移动赋值运算符吗?
Vector &Vector::operator=(Vector &&v)
{
elem = v.elem;
sz = v.sz;
v.elem = nullptr;
v.sz = 0;
return *this;
}
如果两个构造函数都存在,我如何能够检查是否进行了移动而不是复制?
不,不是因为它会使程序泄漏
*this
已经分配的任何内存。
在delete[] elem;
之前使用
elem = v.elem;
或使用 std::swap
存储 v
内存,并在内存被销毁时让 v
释放它:Vector &Vector::operator=(Vector&& v)
{
std::swap(elem, v.elem);
sz = v.sz;
return *this;
}