When are C ++ destructors explicitly called?

When do you need to explicitly call a destructor?

+4
source share
3 answers

When you use placement, new is the common reason (the only reason?):

struct foo {}; void* memoryLocation = ::operator new(sizeof(foo)); foo* f = new (memoryLocation) foo(); // note: not safe, doesn't handle exceptions // ... f->~foo(); ::operator delete(memoryLocation); 

This is mainly present in dispensers (used by containers), in the construct and destroy functions, respectively.

Otherwise, no. Stack allocation will be performed automatically, as will be the case with delete pointers. (Use smart pointers!)

Well, I suppose this is another reason: when you want undefined behavior. Then feel free to call him as many times as you want ... :)

+9
source

Not. You do not need to explicitly call the destructor (other than posting a new one ).

(shameless C ++ FAQ Lite plug;>)

In an extended note, calling destructors is a compiler guarantee - with a new one in the target distribution, you violate this guarantee - which is an absolutely dangerous thing. If you need special allocation, it is usually better to write custom allocators and / or redefine new / delete.

Also note that calling the destructor clearly can have extreme complications, and should not be done in any other case than the case mentioned above.

+4
source

The destructor is called automatically for objects such as automatic storage, when the object leaves the area and the destructor for objects on the heap, is called when the delete operator is used on them.

0
source

Source: https://habr.com/ru/post/1298949/


All Articles