常数值变更 [英] Constant value changing

查看:63
本文介绍了常数值变更的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个结构定义:

Suppose I have a struct definition:

struct thing
{
    thing* x;
    int z;

    thing() : x(this), z(0) {}
    void foo() const
    {
        this->x->z++;
    }
};

请注意,我创建了一个指向自己的可变指针(邪恶的笑声)

Note that I create a mutable pointer to myself (evil laugh)

然后我以后可以这样使用:

And then I can use this later like this:

int main()
{
    const thing c;
    c.foo();
    assert(c.z == 1);
    c.foo();
    assert(c.z == 2);
    return c.z;
}

如您所见,我似乎可以更改一个常数。 ....这是UB吗?

And as you can see it seems that I can change a constant value......is this UB?

推荐答案

[dcl.type.cv] p4:

[dcl.type.cv]p4:


除了任何声明为 mutable ([dcl.stc])的类成员可以修改
,尝试在
生存期内修改([expr.ass],[expr.post.incr],
[expr.pre.incr])const对象([basic.type.qualifier])( [basic.life])导致行为不确定。

Except that any class member declared mutable ([dcl.stc]) can be modified, any attempt to modify ([expr.ass], [expr.post.incr], [expr.pre.incr]) a const object ([basic.type.qualifier]) during its lifetime ([basic.life]) results in undefined behavior.

[basic.type.qualifier] p1:

[basic.type.qualifier]p1:


常量对象是类型为 const T 的对象或非可变对象

A const object is an object of type const T or a non-mutable subobject of such an object.

cz 是一个const对象,因为它是 c 的不可变量子对象。您的代码尝试在其生命周期内对其进行修改。因此,该代码具有未定义的行为。

c.z is a const object, because it is a non-mutable subobject of c. Your code attempts to modify it during its lifetime. It follows that the code has undefined behavior.

这篇关于常数值变更的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆