c++ how Why can destructors change the state of constant objects?

const object in c++ (2)

why can the destructor change this state?

Because it may be useful to be able to change the state of objects in the destructor whether they were const or not.

And because it doesn't matter for encapsulation. The lifetime has ended, so no-one can see the object in the modified state anyway.

And because the standard (quoting from the draft) says so:


The address of a destructor shall not be taken. A destructor can be invoked for a const, volatile or const volatile object. const and volatile semantics ([dcl.type.cv]) are not applied on an object under destruction. They stop being in effect when the destructor for the most derived object ([intro.object]) starts.


I know that it is not allowed to modify the state of a constant object but why can the destructor change this state?

class A
        i = 2; //?

    void test() const
        //i = 1; //Not allowed

    int i = 0;

int main()
    const A o;

As soon as the destructor is executed, the lifetime of the object has already ended. It doesn't make any sense to disallow operations that modify state, because this modified state will never be seen by any caller that is part of well-behaved code. Also, once the lifetime has ended, it doesn't matter whether the object has been const beforehand or not. This is the same reasoning behind constructors not being const -qualified special member functions. They setup an object before its lifetime. Once it's alive, it can be const , beforehand, that makes no sense and would be of little value.