Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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(); } 
like image 392
Igor Avatar asked Jul 10 '19 11:07

Igor


People also ask

Can a destructor be const?

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.

What is the main purpose of 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.

How does a destructor work in C++?

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() .

Does the destructor remove memory allocated to an object?

A destructor only destroys and cleans up the object. It does not deallocate the memory.


2 Answers

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.

like image 156
eerorika Avatar answered Oct 26 '22 14:10

eerorika


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.

like image 28
lubgr Avatar answered Oct 26 '22 15:10

lubgr