How do I call a destructor in C++?

 


 

 

 

Explicit destructor calls are rarely used in C++. First, if the object has automatic, thread-local, or static storage duration, and you explicitly call the destructor, then the destructor will get called a second time when the block, thread, or program (respectively) ends, which will cause undefined behaviour.

  1. { 
  2. T x; 
  3. x.~T(); // destroys x 
  4. } // whoops! x gets destroyed a second time here :( 

Second, even when the object is dynamically allocated, you usually should use something like std::unique_ptr which will automatically call the destructor for you. Third, even if for some reason you need to manage memory manually, usually you will want to destroy the object at the same time as you dispose of its storage. This is done using delete:

  1. auto p = new T; 
  2. // ... 
  3. delete p; // calls T::~T(), then deallocates the memory 

The main situation where you need to explicitly call a destructor is when you have created an object inside a pre-existing buffer:

  1. std::aligned_storage_t<sizeof(T), alignof(T)> storage; 
  2. auto p = new (&storage) T; // `p` points to `T` object created inside `storage` 
  3. // ... 
  4. p->~T(); // `T` object is destroyed, but `storage` is still alive 
  5. // ... 
  6. // `storage` goes out of scope and is deallocated 

The syntax for explicit destructor calls, when you need them, is x.~T() where T is a class type and x is an object of type T. The object x is thus destroyed. If p is a pointer to type T, then the syntax p->~T() may be used.

Since C++17, there is a library function that can be used to avoid having to write out the name of the type redundantly: std::destroy_at(p) is equivalent to p->~T() where T is the type that p points to.

 

Comments

Popular posts from this blog