What are the instances where you need to explicitly call a destructor?
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... :)
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.