[英]Why can I move an object with deleted move constructor and assignment operator?
[英]can I call destructor in move assignment operator?
在移動分配操作員里面調用一個d-tor好習慣嗎?
這里有一些示例代碼:
VectorList &operator = (VectorList &&other){
~VectorList(); // if this is not a good practice,
// I will need to paste whole d-tor here.
_buffer = std::move(other._buffer );
_dataCount = std::move(other._dataCount );
_dataSize = std::move(other._dataSize );
other._clear();
return *this;
}
我應該使用此代碼,還是應該使用swap()與移動構造對象?
~VectorList
不僅運行dtor體中的代碼:它實際上會破壞對象。
之后,存儲空間未使用。 您可以使用構造函數在那里構造一個新對象,但只是訪問成員將是未定義的行為,或者需要語言律師找到允許它被定義的漏洞。
即使被定義,它也是危險的,因為在銷毀自動存儲對象時拋出的異常是壞消息。 另外,如果指定的類實際上是派生類型,則dtor調用本身就是UB!
這兩種方法都不值得。 好處太小了。
更好的選擇是copy-swap(至少很容易糾正:它可以阻止一些優化),或者從dtor和賦值中重構出“clear”代碼。 然后在兩個地方打電話給它。
Scott Meyers說不要使用swap()
: http : //scottmeyers.blogspot.sg/2014/06/the-drawbacks-of-implementing-move.html
關於您當前的實施,似乎您可以更簡單地做到這一點。 我想析構函數實際上刪除了_buffer
並且沒有其他功能。 如果這是真的,你應該用delete _buffer
替換你更難delete _buffer
顯式析構函數調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.