Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are C++ destructors explicitly called?

Tags:

c++

destructor

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

like image 326
jasonline Avatar asked Dec 13 '22 00:12

jasonline


1 Answers

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... :)

like image 159
GManNickG Avatar answered Dec 28 '22 23:12

GManNickG