๐ C++ Destructors Notes: Comprehensive Guide
Playlist Link: C++ Series by The Cherno
๐ Introduction to Destructors
Video Reference: Destructors in C++
- Purpose: Destructors clean up resources when an object is destroyed (e.g., memory deallocation, closing files).
- Called Automatically:
- When stack-allocated objects go out of scope.
- When
deleteis called on heap-allocated objects.
๐๏ธ Constructor vs. Destructor Syntax
Video Reference: Syntax Example
Example Code:
class Entity {
public:
float x, y;
// Constructor (Initialization)
Entity() : x(0.0f), y(0.0f) {
std::cout << "Created Entity!" << std::endl;
}
// Destructor (Cleanup)
~Entity() {
std::cout << "Destroyed Entity!" << std::endl;
}
};
- Constructor: Runs when the object is created (e.g.,
Entity e;). - Destructor: Runs when the object is destroyed (e.g., end of scope or
delete).
๐๏ธ Stack vs. Heap Allocation
Video Reference: Stack/Heap Behavior
Example 1: Stack Allocation
void Function() {
Entity e; // Constructor called
e.Print(); // Use the object
} // Destructor called automatically when scope ends
Output:
Created Entity!
Destroyed Entity!
Example 2: Heap Allocation
Entity* e = new Entity(); // Constructor called
delete e; // Destructor called manually
๐ก Use Cases for Destructors
Video Reference: Real-World Examples
Destructors are critical for:
- Freeing heap memory allocated in the constructor.
- Closing files/database connections opened by the object.
- Releasing other resources (e.g., GPU textures, network sockets).
Example: Preventing Memory Leaks
class Buffer {
private:
int* data;
public:
Buffer(int size) { data = new int[size]; }
~Buffer() { delete[] data; } // Cleanup in destructor
};
โ ๏ธ Manual Destructor Calls (Rare!)
Video Reference: Manual Destruction
- Avoid unless necessary! Destructors are designed to be automatic.
Entity e; e.~Entity(); // Manual call (risky, may cause double-free errors)Output:
Destroyed Entity! Destroyed Entity! // Crash risk if memory is freed twice
โ Key Takeaways
- Destructors ensure proper cleanup of resources.
- Stack objects auto-destroy at scope end; heap objects require
delete. - Never manually call destructors unless you fully understand the implications.
๐ผ Video Transcript & Main Link: Full Video
Use this guide to avoid rewatching the video! Revisit sections via timestamps if needed. ๐
