将赋值移动到具有 const 值的对象
move assignment to object with const value
我有这样的结构:
struct OBJ {
int x;
const int y;
OBJ& operator=(OBJ &&oth)
{
y = oth.y; // this is disallowed
return *this;
}
}
和示例代码
void func() {
static OBJ obj;
OBJ other; // random values
if(conditon)
obj = std::move(other); //move
}
我理解为 obj
是 非 const OBJ 与 const 成员 y
。我不能只改变 y 但我应该能够改变整个对象(调用析构函数和构造函数)。这是否可能或唯一正确的解决方案是在 y
之前删除我的 const
,并记住不要意外更改?
我需要在 func
调用之间存储我的 static obj
,但如果条件为真,我想移动其他对象来代替这个静态对象。
你做的构造函数是错误的。构造函数应该初始化,而不是赋值:
OBJ(OBJ &&oth) : y(oth.y) {}
// ^^^^^^^^^^
此外,构造函数不能 return *this
,因为它们没有 return 类型。
您的 class 的赋值运算符没有意义,因为 class 具有不可分配的成员(即常量)。 (你当然可以编写一个不修改 const 成员的自定义赋值,但那样你就会有一个真正奇怪的 class,它的行为非常令人惊讶。)
这样写移动赋值运算符怎么样:
OBJ& operator=(OBJ&& other) {
this->~OBJ();
new(this) OBJ(other.x, other.y);
return *this;
}
您还需要一个构造函数:
OBJ(const int x, const int y)
: x(x), y(y)
{
}
我建议搬到 std::unique_ptr
:
void func() {
static std::unique_ptr<OBJ> obj = std::make_unique<OBJ>();
std::unique_ptr<OBJ> other = std::make_unique<OBJ>(); // random values
if(condition)
obj = std::move(other); //move
}
在需要移动无法移动的东西、保存未知的多态类型或任何其他您无法处理实际类型的情况下,这应该是您的选择。
我有这样的结构:
struct OBJ {
int x;
const int y;
OBJ& operator=(OBJ &&oth)
{
y = oth.y; // this is disallowed
return *this;
}
}
和示例代码
void func() {
static OBJ obj;
OBJ other; // random values
if(conditon)
obj = std::move(other); //move
}
我理解为 obj
是 非 const OBJ 与 const 成员 y
。我不能只改变 y 但我应该能够改变整个对象(调用析构函数和构造函数)。这是否可能或唯一正确的解决方案是在 y
之前删除我的 const
,并记住不要意外更改?
我需要在 func
调用之间存储我的 static obj
,但如果条件为真,我想移动其他对象来代替这个静态对象。
你做的构造函数是错误的。构造函数应该初始化,而不是赋值:
OBJ(OBJ &&oth) : y(oth.y) {}
// ^^^^^^^^^^
此外,构造函数不能 return *this
,因为它们没有 return 类型。
您的 class 的赋值运算符没有意义,因为 class 具有不可分配的成员(即常量)。 (你当然可以编写一个不修改 const 成员的自定义赋值,但那样你就会有一个真正奇怪的 class,它的行为非常令人惊讶。)
这样写移动赋值运算符怎么样:
OBJ& operator=(OBJ&& other) {
this->~OBJ();
new(this) OBJ(other.x, other.y);
return *this;
}
您还需要一个构造函数:
OBJ(const int x, const int y)
: x(x), y(y)
{
}
我建议搬到 std::unique_ptr
:
void func() {
static std::unique_ptr<OBJ> obj = std::make_unique<OBJ>();
std::unique_ptr<OBJ> other = std::make_unique<OBJ>(); // random values
if(condition)
obj = std::move(other); //move
}
在需要移动无法移动的东西、保存未知的多态类型或任何其他您无法处理实际类型的情况下,这应该是您的选择。