[英]Move construction and assignment of class with constant member
我有一個 class 和一個需要移動構造函數和賦值的 const 成員。
我通過以下方式實現它:
struct C
{
const int i;
C(int i) : i{i} {}
C(C && other) noexcept: i{other.i} {}
C & operator=(C && other) noexcept
{
//Do not move from ourselves or all hell will break loose
if (this == &other)
return *this;
//Call our own destructor to clean-up before moving
this->~C();
//Use our own move constructor to do the actual work
new(this) C {std::move(other)};
return *this;
}
//Other stuff here (including the destructor)....
}
這可以按預期編譯和工作。
問題是這是否是實現這種移動分配的正常方式,還是有一種不那么人為的方式來做到這一點?
不幸的是,這是未定義的行為。 您不能像這樣覆蓋 const object 並在之后以相同的名稱引用它。 [basic.life]/8涵蓋了這一點
If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if: [...]
- 原始 object 的類型不是 const 限定的,並且,如果 class 類型不包含任何類型為 const 限定或引用類型的非靜態數據成員,[...]
簡單的解決方法是使i
成為非 const 和私有的,只需使用 getter 來阻止任何修改的發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.