交换const成员不确定的行为吗? 17

发布于 2025-01-21 17:23:30 字数 576 浏览 1 评论 0 原文

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;
}

https://godbolt.org/z/E3ETx8a88

Is this swapping UB? Am I mutating anything? UBSAN does not report anything.

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

鸵鸟症 2025-01-28 17:23:30

这交换UB?

是的,这是UB。

我正在变异吗?

您正在突变const对象。这是不允许的。

Is this swapping UB?

Yes, this is UB.

Am I mutating anything?

You are mutating const objects. That's not allowed.

花想c 2025-01-28 17:23:30

这似乎是C ++进化的区域。

它是c ++ 17中的ub,因为

然而,在以后的版本中,该限制已被删除。 。对完整的const对象仍然存在限制。 不能执行此操作。

例如,如果 myint i0(0); const myint i0(0); 即使C ++ 20现在允许修改const sub sub对象,则 ,最好避免 const_cast 并使用它来创建一个分配CTOR。在这种情况下,人们不需要破坏者,因为它可以造成巨大破坏。请注意,必须在C ++ 20之前使用新的位置,这仍然是UB,因为先前不允许Const子对象更改。

constexpr MyInt& operator=(MyInt&& rh)
{
    std::construct_at(&this->i, rh.i);
    return *this;
}

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); was const 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.

constexpr MyInt& operator=(MyInt&& rh)
{
    std::construct_at(&this->i, rh.i);
    return *this;
}
诗笺 2025-01-28 17:23:30

来自 const_cast

通过非const访问路径修改常规对象,并通过非易失性glvalue引用挥发性对象会导致不确定的行为。

是的,那是UB。

From const_cast

Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior.

so Yes, that is UB.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文