Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructors in C++

Tags:

c++

destructor

Does the destructor deallocate memory assigned to the object which it belongs to or is it just called so that it can perform some last minute housekeeping before the object is deallocated by the compiler?

like image 884
shreyasva Avatar asked Mar 23 '10 17:03

shreyasva


2 Answers

The 'compiler' doesn't delete anything. It creates code that does things at runtime.

When you write delete somePointer; the compiler, in essence, writes:

  if ( has_virtual_destructor( * somePointer  ) ) {
       // virtual dispatch to a compiler-generated function
      dynamic_cast< true_dynamic_type * >(somePointer)->destroy_dynamic_type();
       /* contents of true_dynamic_type::destroy_dynamic_type() {
              this->~true_dynamic_type();
              operator delete( this); // executed within class context
       } */
  } else {
      somePointer->~ClassName();
      operator delete(somePointer);
  }

In other words, the destructor gets called, and then operator delete gets called to free the storage.

If the destructor is virtual, a virtual dispatch is used to perform the entire operation on the object in its most-derived form. A common way of implementing this is to add hidden arguments to every virtual destructor.

Note that the top-level if statement isn't really part of the generated code; the compiler makes that decision at compile-time.

like image 76
bmargulies Avatar answered Sep 17 '22 19:09

bmargulies


The destructor is called to allow the object to perform cleanup as well as to destroy any other objects the object itself has created.

The OS will deal with deallocating the object itself after finishing the destructor.

like image 39
damirault Avatar answered Sep 21 '22 19:09

damirault