简体   繁体   中英

Why is it possible to modify object state via const member function that uses pointer to the object's member?

Why doesn't this code produce a compiler error:

class C
{
    int _i{ 123 };
    int* ptr{ &_i };
public:
    int& i() const { return *ptr; }
};

int main()
{
    C const c;
    c.i() += 321;
    return c.i();
}

Is there some words in the standard about this behavior? Of course, maybe there is no point to point to members which can be access directly anyway, but what about owning resources on the heap that can be regarded as part of the object too.

During the construction and destruction of an object, the members are not const. That means you can store a non-const pointer to a member that is going to be const once the object is constructed. Using that pointer to change value of a const object is undefined behavior. Quoting cppreference :

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.

And quoting [dcl.type.cv]/4 :

Except that any class member declared mutable can be modified, any attempt to modify a const object during its lifetime results in undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM