Should I delete this
?
Since I am responsible for memory allocated with new
, should I delete this
from within my class destructor?
In general, you should not delete this
from within a class destructor.
Here's why:
- If the object was allocated on the stack, calling
delete
on it would be undefined behavior, likely crashing your program. - If the object was allocated with
new
, the code that created the object should also be responsible for deleting it. The destructor will be called automatically whendelete
is used on the object from outside the class. - If you
delete this
from within the destructor, and the object was created withnew
, then the external code callingdelete
would be trying to delete an object that was already deleted. This is known as a "double free" error and typically leads to heap corruption.
So in summary, let the code that creates the object also be responsible for deleting the object. The destructor should only clean up resources that the class itself allocated.
Dynamic Memory and the Free Store
Learn about dynamic memory in C++, and how to allocate objects to it using new
and delete