這裏是一個非常簡單的方法來定義一個移動構造函數用於幾乎所有類移動分配:通過破壞+移動構造安全地移動任務嗎?
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;
}
// ...
};
這是程序調用自己的析構函數,然後放置在this指針安全新標準C++ 11 ?
你的移動構造函數最好是'noexcept',否則你將試圖銷燬一個已經被銷燬的對象,如果它在UB-land中拋出並且漫步。 – ildjarn
移動/複製分配的一個好方法是簡單地[按值取參數](http://stackoverflow.com/questions/9746748/does-it-make-sense-to-reuse-destructor-logic-by-使用-stdswap-IN-A-MOVE-分配/ 9746772#9746772)。用戶將移動構建值參數或複製構建它(或者隱藏)。然後您可以使用'std :: swap'將該值交換到您的對象中。 –