Constant value changing


New Member
Suppose I have a struct definition:
struct thing
    thing* x;
    int z;

    thing() : x(this), z(0) {}
    void foo() const
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;;
    assert(c.z == 1);;
    assert(c.z == 2);
    return c.z;
And as you can see it seems that I can change a constant this UB?


Thành viên BQT
Except that any class member declared mutable ([]) can be modified, any attempt to modify ([expr.ass], [], [expr.pre.incr]) a const object ([basic.type.qualifier]) during its lifetime ([]) results in undefined behavior.
A const object is an object of type const T or a non-mutable subobject of such an object.
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.

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.