Dynamic Memory and the Free Store

Should I delete this?

Since I am responsible for memory allocated with new, should I delete this from within my class destructor?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved