Constant value changing

  • A+

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



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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: