Let the destructor do the cleanup
The objective is to write classes that cannot leak, and to know which special member functions a resource-owning class needs.
RAII (Resource Acquisition Is Initialisation) is C++'s central idiom: wrap each resource (heap memory, a file, a socket, a mutex lock, a database transaction) in an object whose constructor acquires it and whose destructor releases it. Because the language guarantees that the destructor of every fully constructed automatic object runs when its scope ends, whether by falling off the end, return, break or a thrown exception, the release cannot be forgotten.
You already use RAII: std::vector frees its buffer, std::string its characters, std::fstream closes its file, std::lock_guard unlocks its mutex, and std::unique_ptr deletes its object (smart pointers are covered in QD04).
Here is a minimal file handle around the C API:
#include <cstdio>
#include <iostream>
#include <stdexcept>
class File {
public:
File(const char* path, const char* mode) : f_(std::fopen(path, mode)) {
if (!f_) throw std::runtime_error("cannot open file");
std::cout << "opened " << path << '\n';
}
~File() {
std::fclose(f_);
std::cout << "closed\n";
}
File(const File&) = delete; // one owner per handle:
File& operator=(const File&) = delete; // copying would close it twice
std::FILE* get() const { return f_; }
private:
std::FILE* f_;
};
void write_fills(bool fail) {
File out("fills.csv", "w");
std::fputs("id,qty\n", out.get());
if (fail) throw std::runtime_error("risk check failed");
std::fputs("1,100\n", out.get());
} // ~File runs here on both paths
int main() {
write_fills(false);
try {
write_fills(true);
} catch (const std::exception& e) {
std::cout << "caught: " << e.what() << '\n';
}
}
opened fills.csv
closed
opened fills.csv
closed
caught: risk check failed
"closed" prints before "caught": stack unwinding runs ~File as the exception leaves write_fills, before the handler runs. If fopen fails, the constructor throws, no File object exists, and no destructor runs, which is correct because there is nothing to close. The deleted copy operations matter just as much as the destructor; the next section explains why.
The rules of zero, three and five
The compiler generates five special members for you when you do not declare them: the destructor, copy constructor, copy assignment, move constructor and move assignment. The generated copies copy each member. For a raw pointer member that means copying the address, not the data it points to, so two objects end up owning one buffer and both destructors delete[] it: a double free.
- Rule of three: if a class needs a user-written destructor, copy constructor or copy assignment, it almost certainly needs all three, because the destructor's existence means the class owns something that the default memberwise copy will share.
- Rule of five: since C++11, add the move constructor and move assignment. Declaring a destructor or a copy operation suppresses the implicit move operations, so "moves" silently fall back to copies. Move semantics are QD04's topic; here, know that the five travel together, and that
= delete(as inFile) or= defaultare valid ways to "write" one. - Rule of zero: best of all, do not own raw resources directly. Build classes from members that already manage themselves (
std::vector,std::string,std::unique_ptr, aFileclass), and write none of the five. Only small, dedicated wrapper classes should follow the rule of five.
#include <iostream>
#include <string>
#include <vector>
// Rule of zero: members already manage themselves, so write no special members.
struct PriceSeries {
std::string symbol;
std::vector<double> prices;
};
int main() {
PriceSeries a{"ESZ6", {100.0, 100.25, 100.5}};
PriceSeries b = a; // deep copy, generated by the compiler
b.prices[0] = 99.5;
std::cout << a.prices[0] << ' ' << b.prices[0] << '\n'; // prints: 100 99.5
}
Worked example
fix a class that owns a raw buffer
A colleague wrote:
class PriceSeries {
public:
explicit PriceSeries(std::size_t n) : n_(n), data_(new double[n]()) {}
~PriceSeries() { delete[] data_; }
double& operator[](std::size_t i) { return data_[i]; }
private:
std::size_t n_;
double* data_;
};
PriceSeries a(3);
PriceSeries b = a;
What goes wrong, and how do you fix it (a) by following the rule of three and (b) by following the rule of zero?
Show solutionHide solution
Diagnosis. PriceSeries b = a; uses the compiler-generated copy constructor, which copies n_ and the pointer data_. Now a and b share one buffer: writing b[0] changes a[0], and at the end of scope both destructors run delete[] on the same address, which is undefined behaviour (typically a crash in the allocator). Assignment c = a has the same problem and also leaks c's original buffer.
(a) Rule of three. Write a deep-copying copy constructor and an assignment operator that is safe if allocation throws:
#include <algorithm>
#include <cstddef>
#include <iostream>
class PriceSeries {
public:
explicit PriceSeries(std::size_t n) : n_(n), data_(new double[n]()) {}
~PriceSeries() { delete[] data_; }
PriceSeries(const PriceSeries& other) // deep copy
: n_(other.n_), data_(new double[other.n_]) {
std::copy(other.data_, other.data_ + n_, data_);
}
PriceSeries& operator=(const PriceSeries& other) {
if (this != &other) {
double* fresh = new double[other.n_]; // allocate first: if this throws,
std::copy(other.data_, other.data_ + other.n_, fresh);
delete[] data_; // *this is still unchanged
data_ = fresh;
n_ = other.n_;
}
return *this;
}
double& operator[](std::size_t i) { return data_[i]; }
std::size_t size() const { return n_; }
private:
std::size_t n_;
double* data_;
};
int main() {
PriceSeries a(3);
a[0] = 100.0;
PriceSeries b = a; // copy constructor
b[0] = 99.5;
PriceSeries c(1);
c = a; // copy assignment
c[0] = 101.25;
std::cout << a[0] << ' ' << b[0] << ' ' << c[0] << ' ' << c.size() << '\n';
}
100 99.5 101.25 3
Each object now has its own buffer: changing b and c leaves a[0] at 100, and c took a's size of 3. The assignment allocates and copies before freeing the old buffer, so if new throws std::bad_alloc, *this is untouched (the strong guarantee, below). The self-assignment test stops a = a from freeing its own data. Moves still fall back to these copies, which the rule of five would fix.
(b) Rule of zero. Replace double* data_ and n_ with one std::vector<double> data_. Delete the destructor and both copy operations. The vector already deep-copies, frees, moves and stays exception-safe, and size() becomes data_.size(). Thirty lines become five, and that is the answer an interviewer wants to hear second, after you have shown you understand the first.
Exception safety and lock_guard
Exception-safety guarantees describe what state a function leaves behind if it throws:
- No-throw: it never throws. Destructors,
swapand memory release should be here. Destructors are implicitlynoexcept; a destructor that throws during unwinding callsstd::terminate. - Strong: if it throws, the program state is as if it was never called (commit-or-rollback).
std::vector::push_backgives this for most element types; the copy assignment above does too. - Basic: if it throws, no resources leak and all invariants hold, but the state may have changed.
RAII gives you the basic guarantee almost for free. Locking is the textbook case: a manual m.lock(); ... m.unlock(); leaves the mutex locked forever if anything in between throws or returns early, and the next caller deadlocks. std::lock_guard locks in its constructor and unlocks in its destructor:
#include <iostream>
#include <map>
#include <mutex>
#include <stdexcept>
#include <string>
std::mutex book_mutex;
std::map<std::string, int> positions;
void apply_fill(const std::string& sym, int qty) {
std::lock_guard<std::mutex> lock(book_mutex); // locks here
if (qty == 0) throw std::invalid_argument("zero fill");
positions[sym] += qty;
} // unlocks here, whether we return or throw
int main() {
apply_fill("ESZ6", 5);
try {
apply_fill("ESZ6", 0);
} catch (const std::exception& e) {
std::cout << "rejected: " << e.what() << '\n';
}
// If the throw had left the mutex locked, this call would deadlock.
apply_fill("ESZ6", -2);
std::cout << "ESZ6 position " << positions["ESZ6"] << '\n';
std::cout << "try_lock after calls: " << (book_mutex.try_lock() ? "free" : "held") << '\n';
book_mutex.unlock();
}
rejected: zero fill
ESZ6 position 3
try_lock after calls: free
The position is ; the rejected fill changed nothing. Related tools: std::scoped_lock locks several mutexes without deadlock, and std::unique_lock can be unlocked early or handed to a condition variable (QD06). A common bug is a guard with no name: std::lock_guard<std::mutex>{book_mutex}; creates a temporary that locks and unlocks at the semicolon, so the rest of the scope runs unprotected (clang 17 warns: "ignoring temporary created by a constructor declared with 'nodiscard' attribute"). With parentheses instead of braces it parses as a declaration of a new variable called book_mutex and fails to compile.
Worked example
what runs when a constructor throws?
Predict the output:
#include <iostream>
#include <stdexcept>
struct Res {
const char* n;
explicit Res(const char* s) : n(s) { std::cout << "acquire " << n << '\n'; }
~Res() { std::cout << "release " << n << '\n'; }
};
struct Session {
Res socket{"socket"};
Res buffer{"buffer"};
Session() {
std::cout << "Session body\n";
throw std::runtime_error("login rejected");
}
~Session() { std::cout << "~Session\n"; }
};
int main() {
try {
Session s;
} catch (const std::exception& e) {
std::cout << "caught: " << e.what() << '\n';
}
}
Show solutionHide solution
Members are built first, in declaration order: acquire socket, acquire buffer, then Session body. The body throws, so the Session object never finished construction. The rule is: the destructors of fully constructed sub-objects run, but the destructor of the object whose constructor threw does not. So buffer and socket are released in reverse order, ~Session never prints, and then the handler runs.
acquire socket
acquire buffer
Session body
release buffer
release socket
caught: login rejected
The lesson: if Session had acquired its socket with a raw new in the constructor body and planned to free it in ~Session, the throw would leak it. Holding each resource in its own RAII member means a partially built object still cleans up after itself.
Knowledge check
A class holds int* buf_ allocated with new int[n] in its constructor and frees it in its destructor. It declares no copy operations. What happens with { Holder a(4); Holder b = a; }?
Knowledge check
A constructor initialises two RAII members and then throws from its body. Which destructors run?
Knowledge check
Which statement best describes the rule of zero?
Key takeaways
- RAII: acquire in the constructor, release in the destructor. Destructors of fully constructed objects run on every exit path, including exceptions.
- The default copy of a raw-pointer member shares ownership and leads to double frees. Define or delete all of the destructor and copy (and move) operations together, or better, own nothing raw.
- Rule of zero for ordinary classes; rule of five only for small resource wrappers.
- If a constructor throws, its members are cleaned up but its own destructor does not run.
- Use
std::lock_guard(orstd::scoped_lock) instead of manual lock/unlock, and give the guard a name.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).