Question

Whenever we are writing destructors in C++ (though this concept could apply in other languages) could we just not write

delete this;

and it would delete whatever data is inside of the class? Is this a good or bad idea? If it is bad, would this not delete all the memory we had allocated to the object?

Was it helpful?

Solution

What does a delete expression do?

  1. It invokes the destructor on the pointed-to data.
  2. It frees memory that was allocated with new.

Since a delete will invoke a destructor, delete this inside a destructor makes no sense (I do not know whether this would be an infinite loop, or would be undefined behaviour).

The even more problematic part is that most objects in C++ are not created with the new operator, and therefore should not be explicitly destroyed via delete. Instead, the objects might be local variables that are destroyed when their scope is left – this deterministic destruction enables RAII. Alternatively, the object might be a member of another object. Members will be destroyed after their enclosing object's destructor has run. They do not have to be destroyed explicitly. E.g. assume the following example:

#include <iostream>

class A
{
public:
  ~A() { std::cout << "~A()\n"; }
};

class B
{
  A _a;
public:
  ~B() { std::cout << "~B()\n"; }
};

int main() {
  B b;
  return 0;
}

When the main scope is left, the B b object is destroyed, and its destructor is run. After that, each member is destroyed, so A _a's destructor is executed. Consequently, the output will be

~B()
~A()

If you are using new and delete to manage memory, then it is important to specify who is responsible for making sure an object is deleted. In general, whoever allocated it must also delete it. However, there are some patterns where the object itself is responsible for its own destruction. E.g. an object might be reference-counted, and should delete itself when the reference count drops to zero. (Really, you should be using std::shared_ptr instead.) Or a GUI might have a dialog window class where dialog instances should delete themselves when the user dismisses it.

Licensed under: CC-BY-SA with attribution
scroll top