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:

  1. If the object was allocated on the stack, calling delete on it would be undefined behavior, likely crashing your program.
  2. 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 when delete is used on the object from outside the class.
  3. If you 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.

Dynamic Memory and the Free Store

Learn about dynamic memory in C++, and how to allocate objects to it using new and delete

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Allocating memory in constructors
Is it okay to use new inside a constructor to allocate memory for my class?
When to use the stack vs the heap
How do I decide when to allocate memory on the stack versus the heap?
Identifying Memory Leaks
How can I tell if my C++ program has a memory leak?
Returning from multiple points
What if my function needs to return from multiple points? How can I ensure all allocated memory is freed?
Writing a memory manager
Can I write my own memory manager to replace new and delete?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant