RAII is the core habit of C++, and it means that the resource acquisition is the initialization. Every resource is tied to an object, so the resource is acquired when the object is constructed and it is released when the object is destroyed, automatically, on every path out of the scope. Because C++ guarantees that the destructors run even when an exception unwinds the stack, RAII makes the leaks and the inconsistent state nearly impossible.
The previous lesson in this module covered "How Do You Detect and Prevent Memory Leaks?", and the next lesson in this module is about "What Is the Real Difference Between Stack and Heap?".
The idea in one sentence
Wrap a resource in a class. The constructor acquires it and the destructor releases it. Then you use the object, and you let its lifetime do the work.
#include <fstream>
#include <iostream>
#include <string>
class File {
public:
explicit File(const std::string& path) : file_(path, std::ios::out) {
if (!file_) {
std::cerr << "could not open " << path << '\n';
}
}
~File() {
if (file_.is_open()) {
file_.close();
}
}
void write_line(const std::string& text) {
file_ << text << '\n';
}
bool good() const { return file_.is_open(); }
private:
std::fstream file_;
};
int main() {
{
File log("records.txt");
if (!log.good()) {
std::cerr << "giving up\n";
return 1;
}
log.write_line("first record");
log.write_line("second record");
}
std::cout << "file closed automatically\n";
return 0;
}The output shows the file being closed without a single explicit close call.
file closed automaticallyThe file was opened in the constructor and it was closed in the destructor, and the destructor ran when the block ended.
Why destructors run on the error path
The reason that RAII is not merely a convenience is the exception path. When an exception propagates, C++ unwinds the stack, and it runs the destructor of every object in the frames that it leaves.
#include <iostream>
#include <stdexcept>
class Guard {
public:
explicit Guard(const std::string& label) : label_(label) {
std::cout << "acquired " << label_ << '\n';
}
~Guard() {
std::cout << "released " << label_ << '\n';
}
private:
std::string label_;
};
void risky() {
Guard guard("database connection");
throw std::runtime_error("query failed");
}
int main() {
try {
risky();
} catch (const std::exception& error) {
std::cout << "caught: " << error.what() << '\n';
}
return 0;
}The output shows the guard being released even though the function exited by throwing.
acquired database connection
released database connection
caught: query failedWithout RAII the connection would have been left open. This is the single strongest argument for the pattern, because it is exception-safe by construction.
RAII for every kind of resource
The pattern is not limited to the memory. It works for anything that has to be given back.
the resource the type that handles it
---------------------- -------------------------------------------
memory std::unique_ptr, std::vector, std::string
files std::fstream
locks std::lock_guard
transactions a rollback object
raw handles a class that wraps the C handle
#include <fstream>
#include <iostream>
#include <string>
class Transaction {
public:
explicit Transaction(const std::string& name) : name_(name) {
std::cout << "begin " << name_ << '\n';
}
void commit() {
committed_ = true;
std::cout << "commit " << name_ << '\n';
}
~Transaction() {
if (!committed_) {
std::cout << "rollback " << name_ << '\n';
}
}
private:
std::string name_;
bool committed_ = false;
};
int main() {
{
Transaction good("transfer");
good.commit();
}
{
Transaction bad("audit");
// no commit: the destructor rolls it back
}
return 0;
}The output shows the two outcomes.
begin transfer
commit transfer
begin audit
rollback auditThe three rules of RAII
The first rule is one resource, one object. If a class owns two resources then its destructor has two chances to get one of them wrong. You split it into two classes and you compose them.
The second rule is that you acquire in the constructor and you release in the destructor. Nothing should be half-acquired when the constructor finishes, and nothing should be released before the destructor begins.
The third rule is that you keep the scope as narrow as possible. The resource is released when the scope ends, so you make the scope short. A lock that is held for a whole function is a lock that is held for far too long.
#include <iostream>
#include <string>
class ScopedName {
public:
explicit ScopedName(const std::string& name) : previous_(name) {
std::cout << "entering " << name << '\n';
}
~ScopedName() {
std::cout << "leaving " << previous_ << '\n';
}
private:
std::string previous_;
};
void process() {
ScopedName scope("processing");
std::cout << "working\n";
}
int main() {
process();
std::cout << "done\n";
return 0;
}The output shows the scope being entered and left exactly once.
entering processing
working
leaving processing
doneRAII and smart pointers
A smart pointer is RAII applied to the memory. The constructor allocates, the destructor frees, and the std::unique_ptr and the std::shared_ptr types add the ownership rules on top. That is why the modern advice is not "be careful with delete" but "let an object own the resource". Once the ownership is expressed in a type, the rest of the language takes care of the details.
Where RAII comes from
The name is not decoration. RAII was the mechanism that C++ adopted from the very beginning so that the objects could own the resources, and it is why a C++ object can represent an open file, a held lock or a reserved block of memory without any special support from the language.
And the idea generalises to anything that has a lifetime. A database transaction, a temporary directory, a lease on a licence, a lock on a mutex. In each case there is an acquire step and a release step, and the release step has to happen exactly once, no matter how the code in between leaves the scope.
And the difference between RAII and a manual cleanup block at the end of a function is the number of exit paths. A function has more exits than you think. There is the normal end, there is the early return, there is the throw, there is the break out of a loop that contains the resource, and there is the return from a nested call. RAII covers all of them at once, because the destructor is attached to the object and not to a line of code.
RAII and containers
Every standard container is a RAII type. A std::vector allocates in its constructor, it grows as you add the elements, and it frees everything in its destructor. A std::string does the same for the characters. A std::unique_ptr does it for a single object.
And that is why the standard library's containers are safe to use inside the functions that throw, and why a vector that was declared before a risky call does not leak when the call fails.
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
std::vector<int> build_records(int count) {
std::vector<int> records;
records.reserve(count);
for (int i = 0; i < count; ++i) {
if (i == 3) {
throw std::runtime_error("record could not be created");
}
records.push_back(i * 10);
}
return records;
}
int main() {
try {
build_records(10);
} catch (const std::exception& error) {
std::cout << "caught: " << error.what() << '\n';
}
return 0;
}The output shows the exception being caught, and the partially built vector having been cleaned up on the way out.
caught: record could not be createdNothing had to be cleaned up by hand, and there is no path through this program that can leak.
Quick reference
- RAII means that a resource is acquired in a constructor and it is released in a destructor.
- The destructors run on every exit path, including when an exception unwinds the stack.
- It applies to the memory, the files, the locks, the transactions and any handle that has to be given back.
- Use one resource per object, and compose rather than combining.
- Keep the scope as narrow as possible, so that the resource is released early.
- The smart pointers are RAII for the memory, and they are the default for a dynamic allocation.
Try it yourself: write a small RAII class that opens a file in its constructor and closes it in its destructor, and then use it inside a function that throws halfway through. Confirm that the file is closed by checking that you can delete it straight afterwards on Windows. Next, add a commit flag so that the destructor only rolls back an uncommitted transaction, and try both of the paths.