jasonline
jasonline

Reputation: 9064

When are C++ destructors explicitly called?

What are the instances where you need to explicitly call a destructor?

Upvotes: 4

Views: 1307

Answers (3)

GManNickG
GManNickG

Reputation: 504333

When you use placement-new is a 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 mostly present in allocators (used by containers), in the construct and destroy functions, respectively.

Otherwise, don't. Stack-allocations will be done automatically, as it will when you delete pointers. (Use smart pointers!)

Well, I suppose that makes one more reason: When you want undefined behavior. Then feel free to call it as many times as you want... :)

Upvotes: 9

Kornel Kisielewicz
Kornel Kisielewicz

Reputation: 57635

No. You never need to explicitly call a destructor (except with placement new).

(shameless C++ FAQ Lite plug ;>)

On an extended note, calling destructors is a guarantee of the compiler -- by using new in a targeted allocation, you break that guarantee -- what is definitively a dangerous thing. If you need special allocation, it's usually better to write custom allocators and/or override new/delete.

Also take note, that calling a destructor explicitly can have extreme complications, and shouldn't be done in any other case than the case mentioned above.

Upvotes: 4

user174084
user174084

Reputation: 1107

Destructor are called automatically for objects of auto storage type when the object leaves scope and destructor for objects on the heap are called when the delete operator is used on them.

Upvotes: 0

Related Questions