Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is taking the address of a destructor forbidden?

C++ standard at 12.4.2 states that

[...] The address of a destructor shall not be taken. [...]

However, one can without any complaints by the compiler take the address of a wrapper around a class destructor, like this:

struct Test {     ~Test(){};      void destructor(){         this->~Test();     } };  void (Test::*d)() = &Test::destructor; 

So what's the rationale behind forbidding to take the address of a destructor directly?

like image 315
Fabio A. Avatar asked Oct 26 '11 15:10

Fabio A.


People also ask

Why are destructors protected?

Use a protected destructor to prevent the destruction of a derived object via a base-class pointer. It limits access to the destuctor to derived classes. And it prevents automatic (stack) objects of class base.

Can destructors take arguments?

A destructor takes no arguments and has no return type. Its address cannot be taken. Destructors cannot be declared const , volatile , const volatile or static . A destructor can be declared virtual or pure virtual .

Does calling delete call the destructor?

The answer is yes. Destructor for each object is called. On a related note, you should try to avoid using delete whenever possible.

What happens when a destructor is private?

When something is created using dynamic memory allocation, it is the programmer's responsibility to delete it. So compiler doesn't bother. In the case where the destructor is declared private, an instance of the class can also be created using the malloc() function.


1 Answers

Constructors and destructors are somewhat special. The compiler often uses different conventions when calling them (e.g. to pass extra hidden arguments). If you took the address and saved it somewhere, the compiler would lose the information that the function is a constructor or destructor, and would not know to use the special conventions.

like image 69
James Kanze Avatar answered Oct 22 '22 09:10

James Kanze