Module 5 · Classes and Objects — topic 3 of 5
Destructors and RAII
Destructors run automatically when objects die. Learn destruction order and RAII — tying resource lifetime to object lifetime — plus the Rule of Three/Five/Zero.
Learning objectives
- Write destructors and predict when they run
- Apply RAII to files, memory and locks
- Explain the Rule of Three/Five/Zero
Definition
A destructor (~ClassName()) is a special member function called automatically when an object's lifetime ends; RAII (Resource Acquisition Is Initialisation) is the idiom of acquiring a resource in a constructor and releasing it in the destructor.Introduction
In C you must remember to fclose, free and unlock on every path out of a function. In C++ you wrap the resource in an object whose destructor releases it; leaving the scope — normally, by return or by an exception — runs the destructor automatically.
Why it matters
RAII is the single most important C++ idiom; it is how std::vector, std::string, std::fstream, std::unique_ptr and std::lock_guard work.
It makes leaks practically impossible and keeps code exception-safe.
Detailed explanation
A local object's destructor runs when execution leaves its scope. Objects are destroyed in reverse order of construction.
Members are destroyed after the destructor body runs, in reverse declaration order.
Rule of Three: if a class needs a custom destructor, copy constructor or copy assignment, it probably needs all three. Rule of Five adds move constructor and move assignment. Rule of Zero: prefer members that manage themselves (vector, string, unique_ptr) so you need none of them.
Destructors should not throw; they are implicitly noexcept.
Syntax
- The destructor has no parameters and no return type.
= deleteforbids copying a resource owner that can't be shared.- There is exactly one destructor per class.
Code examples
Destruction order
construct A construct B construct C destroy C destroy B end of main destroy A
Destructors run on early return
locked unlocked -1
More examples
An RAII buffer following the Rule of Five
hello Jello 0
Step-by-step explanation
- The constructor allocates; the destructor frees — no manual delete anywhere else.
- The copy constructor allocates new memory and copies the bytes (a deep copy), so changing
bleavesaalone. - The move constructor takes
a's pointer and leavesaempty, so the memory is freed exactly once. - Copy-and-swap gives a correct, exception-safe assignment operator.
Expected output
Running “An RAII buffer following the Rule of Five” prints exactly:
Practical applications
std::fstreamcloses files in its destructor.std::lock_guardreleases mutexes automatically.- Database and network libraries close connections in destructors.
Best practices
- Follow the Rule of Zero whenever possible.
- Wrap every raw resource in an RAII class.
- Delete copy operations for non-copyable resources.
Common mistakes
Shallow copy of an owning pointer
Avoid
Prefer
The default copy copies the pointer, so both objects delete the same memory. Use self-managing members.
Throwing from a destructor
Avoid
Prefer
Destructors are noexcept; throwing terminates the program.
Important notes
- Objects created with
neware destroyed only whendeleteis called — which is why owning raw pointers break RAII unless wrapped in smart pointers. - Static objects are destroyed after main returns, in reverse order of construction.
Key takeaways
- Destructors run automatically at the end of an object's lifetime.
- RAII ties resource release to scope exit.
- Rule of Zero: let members manage resources.
Try it yourself
- 1Write a
Timerclass that prints how many loop iterations ran between construction and destruction (pass the count in). - 2Add tracing output to the Buffer class to show which special member function runs for each line in main.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
7 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat does RAII stand for?
- ModerateWhat is printed?