A destructor is just like any other function. It does not destroy objects. All that happens is that when the compiler has already decided to destroy an object, it will call the destructor so that you can clean up any resource allocations. After that call, the compiler calls the destrcutor on your member variables and after that the object is deleted by the compiler.
Therefore, you can call the destructor anytime you wish to clear out the objects current allocations in the
this object. The usual place where you do this is in the class assignment operator overload. Here the contents of the
this object have to be cleaned up before they are overwritten by the contents of the object on the right of the assignment operator, the RVAL.
The compiler first calls the assignment operator on the class member variables and then calls the assignment operator for the
this object. Each of these assignment operator calls has the following general flow:
-
MyClass MyClass::operator=(const MyClass& rval)
-
{
-
if (this == &rval) return; //do not assign to yourself
-
this->~MyClass(); //call destructor to clean ourselves up
-
-
//do the reallocation here to accommodate the rval members
-
-
return *this;
-
}
-
You could, of course have a private member function call by both the class destructor and by the assignment operator to do this cleanup but often just calling the destructor makes the most sense.