【发布时间】:2012-10-17 00:47:12
【问题描述】:
这是为大多数具有移动构造函数的类定义移动赋值的一种非常简单的方法:
class Foo {
public:
Foo(Foo&& foo); // you still have to write this one
Foo& operator=(Foo&& foo) {
if (this != &foo) { // avoid destructing the only copy
this->~Foo(); // call your own destructor
new (this) Foo(std::move(foo)); // call move constructor via placement new
}
return *this;
}
// ...
};
在标准 C++11 中,调用您自己的析构函数然后在 this 指针上放置 new 的顺序是否安全?
【问题讨论】:
-
你的移动构造函数最好是
noexcept,否则你会尝试摧毁一个已经被摧毁的物体,如果它在UB-land中抛出并徘徊。 -
移动/复制分配的一个好技巧是简单地take the parameter by value。用户将移动构造 value 参数或复制构造它(或隐藏到其中)。然后,您可以使用
std::swap将值交换到您的对象中。
标签: c++ c++11 move-semantics placement-new move-assignment-operator