In general, you should not delete this
from within a class destructor.
Here's why:
delete
on it would be undefined behavior, likely crashing your program.new
, the code that created the object should also be responsible for deleting it. The destructor will be called automatically when delete
is used on the object from outside the class.delete this
from within the destructor, and the object was created with new
, then the external code calling delete
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.
Answers to questions are automatically generated and may not have been reviewed.
Learn about dynamic memory in C++, and how to allocate objects to it using new
and delete