gpt4 book ai didi

c++ - 将赋值 move 到具有 const 值的对象

转载 作者:行者123 更新时间:2023-11-30 02:23:34 25 4
gpt4 key购买 nike

我有一个这样的结构:

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
}

我理解为 objNon const OBJ with const member y。我不能只改变 y 但我应该能够改变整个对象(调用析构函数和构造函数)。这是否可能或唯一正确的解决方案是在 y 之前删除我的 const,并记住不要意外更改?

我需要在 func 调用之间存储我的 static obj,但如果条件为真,我想 move 其他对象来代替这个静态对象。

最佳答案

我建议 move 到 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
}

在需要 move 无法 move 的东西、保存未知的多态类型或任何其他您无法处理实际类型的情况下,这应该是您的选择。

关于c++ - 将赋值 move 到具有 const 值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46115831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com