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... :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With