交换const成员不确定的行为吗? 17
https://godbolt.org/z/e3etx8a8888
这是互换UB吗?我在变异吗?瑞银什么都没有报告。
#include <utility>
struct MyInt
{
MyInt(int ii): i(ii) {}
const int i;
MyInt& operator=(MyInt&& rh)
{
std::swap(const_cast<int&>(i), const_cast<int&>(rh.i));
return *this;
}
};
int main() {
MyInt i0(0);
MyInt i2(2);
i0 = std::move(i2);
return i0.i;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是UB。
您正在突变const对象。这是不允许的。
Yes, this is UB.
You are mutating const objects. That's not allowed.
这似乎是C ++进化的区域。
它是c ++ 17中的ub,因为
然而,在以后的版本中,该限制已被删除。 。对完整的const对象仍然存在限制。 不能执行此操作。
例如,如果
myint i0(0);
是const myint i0(0);
即使C ++ 20现在允许修改const sub sub对象,则 ,最好避免const_cast
并使用它来创建一个分配CTOR。在这种情况下,人们不需要破坏者,因为它可以造成巨大破坏。请注意,必须在C ++ 20之前使用新的位置,这仍然是UB,因为先前不允许Const子对象更改。This seems to be an area of c++ evolution.
It's UB in c++17 because of this restriction on replacing const member objects
However, in later versions, this restriction is mostly removed.. There remains a restriction on complete const objects. For instance you can't do this if
MyInt i0(0);
wasconst MyInt i0(0);
Even though c++20 now allows modification of const sub objects, it's best to avoid
const_cast
and use this to create an assignment ctor. In this case one doesn't need a destructor since it's trivially destructable. Note that one had to use placement new prior to c++20 and that was still UB since const sub objects were not permitted to change previously.来自 const_cast
是的,那是UB。
From const_cast
so Yes, that is UB.