Why can a destructor change the state of a constant object?

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.


For the same reason that the constructor can change the state! These two methods own the object and can do anything they like to create and destroy it.

In particular, the object may have some allocated resources, or contain smart pointers. These must be destroyed by the destructor.

Just wait until you find out about mutable members and rval references!


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:

[class.dtor]

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.

Tags:

C++