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 { public: ~A() { i = 2; //? } void test() const { //i = 1; //Not allowed } int i = 0; }; int main() { const A o; o.test(); }
Destructors cannot be declared const , volatile , const volatile or static . A destructor can be declared virtual or pure virtual . If no user-defined destructor exists for a class and one is needed, the compiler implicitly declares a destructor.
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .
A destructor only destroys and cleans up the object. It does not deallocate the memory.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With