Lesson 5 of 7
Destructors & RAII Preview
The **destructor** (`~ClassName()`) runs exactly when the object's lifetime ends - when it goes out of scope (stack) or when `delete` is called (heap). RAII (Resource Acquisition Is Initialisation) is the pattern of tying resource lifetime to object lifetime: **acquire in constructor, release in destructor**. This makes resource leaks structurally impossible - the destructor always runs, even if an exception is thrown.
Destructors - Lifetime, RAII & Exception Safety
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
// ── Manual resource management - BAD pattern ─────────────────
void bad_pattern() {
FILE* f = fopen("data.txt", "r");
// ... if an exception is thrown here: f is LEAKED
int* arr = new int[1000];
// ... if an exception is thrown here: arr is LEAKED too
fclose(f);
delete[] arr;
// Requires manually calling cleanup on EVERY exit path
}
// ── RAII file handle - destructor guarantees cleanup ──────────
class FileHandle {
FILE* fp_;
std::string path_;
public:
explicit FileHandle(const std::string& path, const char* mode)
: fp_(fopen(path.c_str(), mode))
, path_(path)
{
if (!fp_) {
throw std::runtime_error("Cannot open: " + path);
}
std::cout << "Opened: " << path_ << "
";
}
// No copy - one handle per resource
FileHandle(const FileHandle&) = delete;
FileHandle& operator=(const FileHandle&) = delete;
// Destructor - ALWAYS runs when object goes out of scope
~FileHandle() {
if (fp_) {
fclose(fp_);
std::cout << "Closed: " << path_ << "
";
}
}
FILE* get() const { return fp_; }
bool valid()const { return fp_ != nullptr; }
};
// ── Destructor order - reverse of construction order ─────────
class A { public: A(){ std::cout << "A ctor
"; }
~A(){ std::cout << "A dtor
"; } };
class B { public: B(){ std::cout << "B ctor
"; }
~B(){ std::cout << "B dtor
"; } };
class C {
A a_; // constructed first
B b_; // constructed second
public:
C() { std::cout << "C ctor
"; }
~C() { std::cout << "C dtor
"; }
// Destruction order: ~C → ~B → ~A (reverse of construction)
};
void good_pattern() {
FileHandle f{"README.md", "r"}; // acquired
// ... do work ...
// f goes out of scope → ~FileHandle() runs → fclose guaranteed!
// Throw here? Still fine - destructor runs during stack unwinding
}
int main() {
std::cout << "--- Destruction order ---
";
{ C c; } // A ctor, B ctor, C ctor, C dtor, B dtor, A dtor
std::cout << "
--- RAII ---
";
try {
good_pattern();
FileHandle bad{"nonexistent_file_xyz.txt", "r"}; // throws
} catch (const std::runtime_error& e) {
std::cerr << "Error: " << e.what() << "
";
}
// FileHandle for README.md was already properly closed
return 0;
}Common Mistakes
- Not making the destructor `virtual` in a base class - if you delete a derived object through a base pointer and the base destructor is not virtual, only the base destructor runs. The derived destructor is skipped, causing resource leaks. Always mark base destructors `virtual`.
- Throwing exceptions from a destructor - if a destructor throws during stack unwinding (exception already in flight), `std::terminate` is called. Mark destructors `noexcept` (the default in C++11) and handle errors internally.
- RAII class allowing copy - `FileHandle f2 = f1;` would give two objects trying to `fclose` the same `FILE*` - double-close. Delete the copy constructor/assignment for resource-managing RAII classes.
Tip
Tip
Practice Destructors RAII Preview in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Scope-Based Lifetime, LIFO Stack Destruction Order & Zero Resource Leaks
Practice Task
Note
Practice Task - (1) Write a working example of Destructors RAII Preview from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Destructors RAII Preview is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- The **destructor** (`~ClassName()`) runs exactly when the object's lifetime ends - when it goes out of scope (stack) or when `delete` is called (heap).
- Not making the destructor `virtual` in a base class - if you delete a derived object through a base pointer and the base destructor is not virtual, only the base destructor runs. The derived destructor is skipped, causing resource leaks. Always mark base destructors `virtual`.
- Throwing exceptions from a destructor - if a destructor throws during stack unwinding (exception already in flight), `std::terminate` is called. Mark destructors `noexcept` (the default in C++11) and handle errors internally.
- RAII class allowing copy - `FileHandle f2 = f1;` would give two objects trying to `fclose` the same `FILE*` - double-close. Delete the copy constructor/assignment for resource-managing RAII classes.
Finished this lesson?