Skip to content

RAII and resource management

Difficulty: Beginner

Key concepts

  • RAII
  • resource
  • acquire
  • release
  • destructor
  • scope guard
  • exception safety
  • non-copyable
  • What a resource is, and why releasing it by hand goes wrong.
  • How RAII ties a resource to an object’s lifetime.
  • How to write a small RAII class, and why it must not be copyable.
  • Why RAII makes code safe when exceptions are thrown.

A resource is anything a program acquires and must later give back: memory, an open file, a lock, a network connection, a database transaction, even a “maintenance mode” flag that must be switched off again. Forgetting to give it back is a leak: the file stays open, the lock stays held, and eventually something runs out or blocks.

Here is cleanup done by hand, with the C library’s fopen and fclose:

Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.

manual_close.cpp
// FLAWED. Writes a two-line report to the file at `path`. Returns true if
// both lines were written, false if the file cannot be opened or `overdue`
// is negative, and throws std::invalid_argument if `overdue` is larger
// than `loans`. The file is opened first and the numbers checked later,
// so three paths leave the function while the file is open, and only one
// of them remembers to close it.
bool write_report(const char* path, int loans, int overdue) {
// fopen opens (creating or emptying) the file for writing ("w") and
// hands back a raw pointer to a C library handle, a std::FILE*. The
// handle is a resource: the program must give it back with fclose.
std::FILE* file = std::fopen(path, "w");
// fopen returns nullptr when it fails. Nothing was opened, so there
// is nothing to close: this early return is fine.
if (file == nullptr) return false;
// fprintf writes formatted text; %d is replaced by the int `loans`.
// The C library keeps the text in a buffer in memory; it reaches the
// disk when the buffer fills or when fclose flushes it.
std::fprintf(file, "loans: %d\n", loans);
// Path 2: the file is open, but this return skips the fclose at the
// bottom. The handle leaks, and the buffered "loans" line may never be
// written to disk.
if (overdue < 0) return false; // leak: fclose never called
if (overdue > loans) {
// Path 3: throwing also leaves the function at once, so the fclose
// below is skipped in exactly the same way.
throw std::invalid_argument("more overdue than loans"); // leak again
}
std::fprintf(file, "overdue: %d\n", overdue);
// Path 1, the happy path: the only one that closes the file. Every
// new early return or call that might throw adds another leaking path.
std::fclose(file); // only the happy path gets here
return true;
}

The happy path closes the file. The other two paths out do not: the early return for a negative count, and the exception for an impossible count. Each leaks an open file handle, and the text already written stays in a buffer that fclose would have flushed. It may not reach the disk until the program exits, or at all if the program crashes.

The real problem is structural. With manual cleanup, every path out of the function must remember every resource. Adding one more early return, or calling one more function that might throw, can create a new leak, and nothing warns you.

The previous lessons established two facts. A destructor runs automatically when an object’s lifetime ends, and a local object’s lifetime ends on every path out of its scope: falling off the end, return, break, or an exception passing through. (The exception is a program that is ended abruptly, for example by std::abort, or by an exception that no catch handles, in which case unwinding is not guaranteed.) RAII uses those facts:

  • Acquire the resource in a constructor, and store it in the object.
  • Release it in the destructor.

Now the resource is released exactly when the owning object is destroyed, on every path, without anyone remembering to do it. The name, Resource Acquisition Is Initialization, describes the first half; the second half (release in the destructor) is the part that matters most.

Here is a small RAII class for a C file handle:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file.hpp
// An open file, owned by one object. Creating a File opens the file;
// destroying the File closes it. That pairing is the whole idea of RAII:
// the cleanup is in the destructor, and C++ runs the destructor on every
// path out of the scope that holds the File, so no path can forget it.
// Invariant: handle_ is a valid open file for the whole lifetime of a File.
class File {
public:
// Acquires the resource. Throws std::runtime_error if the file cannot be
// opened, so a File that exists always holds an open handle.
// `mode` is a C mode string: "w" to write (creating or emptying the
// file), "r" to read an existing file.
File(const std::filesystem::path& path, const char* mode);
// Releases the resource, whatever the reason the scope ended.
~File();
// `= delete` removes the copy constructor and copy assignment, so any
// attempt to copy a File is a compile error. A copy would hold the
// same handle, and both destructors would close it: a double release.
File(const File&) = delete; // one owner only
File& operator=(const File&) = delete;
// Writes `text` at the current position. std::string_view is a cheap
// read-only view of someone else's characters (here, often a string
// literal), so nothing is copied to pass it in.
// Throws std::runtime_error if the write fails.
void write(std::string_view text);
// Reads the remaining contents of the file.
[[nodiscard]] std::string read_all();
private:
// A raw pointer to the C library's file handle. File owns it: this
// object, and only this object, will pass it to fclose.
std::FILE* handle_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file.cpp
// Acquire: open the file in the member initializer list, then check.
// fopen wants a C string, so path.string() turns the path into a
// std::string and .c_str() gives a pointer to its characters. If fopen
// fails it returns nullptr, and throwing here means the constructor never
// finishes, so no File object exists. (The destructor only runs for objects
// whose constructor finished, so ~File never sees a null handle.)
File::File(const std::filesystem::path& path, const char* mode)
: handle_(std::fopen(path.string().c_str(), mode)) {
if (handle_ == nullptr) throw std::runtime_error("cannot open " + path.string());
}
// Release: the only fclose in the class. It also flushes any buffered text
// to disk. No null check is needed, because of the constructor's guarantee.
File::~File() { std::fclose(handle_); }
// fwrite copies text.size() items of 1 byte each from text.data() and
// returns how many it wrote. Fewer than asked for means the write failed,
// so the failure is reported as an exception instead of being ignored.
void File::write(std::string_view text) {
if (std::fwrite(text.data(), 1, text.size(), handle_) != text.size()) {
throw std::runtime_error("write failed");
}
}

Read it as an ownership design:

  • The constructor acquires or throws. If fopen fails, the constructor throws, so no File object exists with a null handle. Every member function can rely on the invariant “the handle is open”, and the destructor can call fclose without checking.
  • The destructor releases. It is the only place fclose appears.
  • Copying is deleted. If a File could be copied, two objects would hold the same handle, and both destructors would close it: a double release, which is undefined behaviour. = delete makes copying a compile error. Because the copy operations are declared, File is not movable either for now. (Moving the handle to a new owner is safe; the Rule of Zero and Rule of Five lesson shows how to add it.)

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// The same report as the flawed version, written with a File. When
// `fail_halfway` is true it throws after the first line, standing in for any
// failure in the middle of the work. There is no close call anywhere: the
// local object `report` closes the file however this function is left.
void write_report(const std::filesystem::path& path, bool fail_halfway) {
File report(path, "w"); // acquire
report.write("loans: 3\n");
// Throwing leaves the function here. On the way out, C++ destroys the
// local `report`, so ~File runs and closes the file (stack unwinding).
if (fail_halfway) throw std::runtime_error("lost connection to the catalog");
report.write("overdue: 1\n");
} // release: ~File closes the file
int main() {
// A file name in the system's temporary directory. The `/` operator
// joins two parts of a std::filesystem::path.
const auto path = std::filesystem::temp_directory_path() / "lld_raii_report.txt";
write_report(path, false);
// File(path, "r") with no variable name is a temporary: it opens the
// file, read_all() reads it, and the temporary is destroyed (closing
// the file) at the end of this statement.
std::cout << "complete report:\n" << File(path, "r").read_all();
try {
write_report(path, true);
} catch (const std::runtime_error& error) {
// By the time this catch block runs, `report` inside write_report
// has already been destroyed and the file closed.
std::cout << "failed: " << error.what() << '\n';
}
// The file was still closed (and its buffered text written) on the way out.
// So the file holds the first line only.
std::cout << "partial report:\n" << File(path, "r").read_all();
std::filesystem::remove(path); // delete the temporary file
}
How this code works: write_report, called twice

main calls write_report twice with the same path. Follow what happens to the file each time.

  1. First call, fail_halfway is false. The constructor of report opens the file for writing, which empties it. Both lines are written (into the C library’s buffer). The function reaches its closing brace, report goes out of scope, and ~File calls fclose, which flushes the buffer to disk.
  2. Reading it back. File(path, "r") is a temporary: it opens the file, read_all() returns both lines, and the temporary is destroyed at the ;, closing the file again.
  3. Second call, fail_halfway is true. Opening with "w" empties the file again. The first line is written. Then the throw leaves the function before the second write. As the exception travels out, C++ destroys every local object in the scopes it leaves, so report is destroyed and ~File closes the file, flushing the first line.
  4. The catch in main runs only after that cleanup. It prints the message, and the program carries on normally.
  5. Reading it back again shows only the first line, which proves the file was closed (and flushed) even though the function never reached its end.
Moment File contents on disk
after the first call returns loans: 3 and overdue: 1
second call: just after it opens empty
second call: after ~File runs loans: 3
Expected output
complete report:
loans: 3
overdue: 1
failed: lost connection to the catalog
partial report:
loans: 3

The second call to write_report throws halfway. On the way out of write_report, the exception destroys report, whose destructor closes the file, which also writes the buffered first line to disk. The partial report shows that line. Nothing in write_report mentions cleanup at all.

Each File(path, "r").read_all() also uses RAII: the temporary File opens the file, the contents are read, and the temporary is destroyed (closing the file) at the end of the statement.

RAII: the File destructor releases the handle whether write_report returns normally or throws
Text description of the diagram

main calls write_report, which constructs the File named report; the constructor calls fopen. write_report writes the first line. Then there are two alternatives. On the normal path, it writes the second line and returns. If an exception is thrown instead, the exception propagates towards the caller. On either path, report goes out of scope, so its destructor runs and calls fclose, releasing the file. In the exception case this happens during unwinding, before the caller’s catch block starts.

Diagram source (Mermaid)
sequenceDiagram
participant caller as main
participant fn as write_report
participant file as File report
participant os as C library
caller->>fn: call
fn->>file: construct
file->>os: fopen
fn->>file: write first line
alt normal path
  fn->>file: write second line
  fn-->>caller: return
else exception thrown
  fn-->>caller: exception propagates
end
Note over fn,file: on either path, report goes out of scope
file->>os: fclose (destructor)

RAII is why C++ code rarely has try/finally blocks (C++ has no finally at all): the cleanup lives in destructors, so a function only needs try and catch where it can actually handle an error. Exception safety and failure atomicity builds on this.

Releasing a resource is behaviour, so test it. For a file, the observable effect of closing is that buffered text reaches the disk, so the tests write in an inner scope and then read the file back:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_raii.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure if
// the condition is false; LLD_CHECK_EQ(actual, expected) records one if the
// two values are not equal, and prints both. LLD_CHECK_THROWS(expression,
// type) fails unless the expression throws that type of exception. They
// come from the site's small test header, lld_test.hpp. temp_file(name),
// defined above, is a path with that name in the temporary directory.
// Writes inside an inner block, so `file` is destroyed at the closing
// brace. Reading the file back afterwards proves the destructor closed it
// and flushed the buffered "hello\n" to disk.
LLD_TEST(destructor_closes_and_flushes) {
const auto path = temp_file("lld_raii_test_flush.txt");
{
File file(path, "w");
file.write("hello\n");
} // closed here
// A temporary File opens the file again, this time for reading.
LLD_CHECK_EQ(File(path, "r").read_all(), std::string("hello\n"));
std::filesystem::remove(path);
}
// The same, but the block is left by an exception instead of by reaching
// its end. The first line being on disk proves ~File still ran.
LLD_TEST(file_is_closed_when_an_exception_leaves_the_scope) {
const auto path = temp_file("lld_raii_test_throw.txt");
try {
File file(path, "w");
file.write("first line\n");
throw std::runtime_error("interrupted");
} catch (const std::runtime_error&) {
// Empty on purpose: the test only needs the exception to leave the
// try block. `file` was destroyed before this block started.
}
LLD_CHECK_EQ(File(path, "r").read_all(), std::string("first line\n"));
std::filesystem::remove(path);
}
// The directory "lld_raii_no_such_dir" does not exist, so opening a file
// inside it for reading fails, and the constructor must throw rather than
// create a File with no handle.
LLD_TEST(opening_a_missing_file_throws) {
LLD_CHECK_THROWS(File(temp_file("lld_raii_no_such_dir") / "x.txt", "r"),
std::runtime_error);
}
// The exercise answer: the guard switches maintenance on while it exists
// and off when it is destroyed, both at the end of a block and when an
// exception leaves the block.
LLD_TEST(maintenance_ends_on_every_path) {
Catalog catalog;
{
const MaintenanceWindow window(catalog);
LLD_CHECK(catalog.in_maintenance()); // on while the guard lives
}
LLD_CHECK(!catalog.in_maintenance()); // off after the closing brace
try {
const MaintenanceWindow window(catalog);
throw std::runtime_error("reindex failed");
} catch (const std::runtime_error&) {
}
LLD_CHECK(!catalog.in_maintenance()); // off after an exception too
}

The second test throws in the middle of the scope and checks that the first line was still written. The last test checks the exercise answer below. The same tests also run under AddressSanitizer, which reports memory leaks when the program ends; it does not track every kind of handle, so the file-content checks matter.

The idiom fits any “begin” that needs a matching “end”:

  • Locks. std::lock_guard and std::scoped_lock lock a mutex when constructed and unlock it when destroyed (the concurrency lessons).
  • Memory. std::vector, std::string, and std::unique_ptr free their memory in their destructors (the smart pointers lesson).
  • Transactions. An object can roll back a database transaction in its destructor unless commit() was called first.
  • Temporary state. A scope guard restores a setting when a scope ends, as in the exercise below.

Write one when you work with a resource that has an explicit release function and no standard wrapper: a C library handle, an operating system resource, or a begin/end pair in your own design.

Do not write one when a standard type already does the job: std::fstream for files, std::vector or std::unique_ptr for memory, std::lock_guard for mutexes. And do not use RAII for work that can fail in ways the caller must hear about. A destructor cannot usefully throw (it is noexcept by default, so an escaping exception terminates the program), so it cannot report failure to its caller. If releasing can fail meaningfully (for example, the final write of a file that must be complete), also offer an explicit close() that reports the error, and let the destructor clean up quietly if close() was never called.

  • Manual release in every path. It works until someone adds a path. Put the release in a destructor.
  • A copyable resource owner. Two copies release the same resource twice. Delete the copy operations (or define them to duplicate the resource properly).
  • Acquiring in an init() function instead of the constructor. The object can then exist without its resource, and every function must check.
  • Throwing from a destructor. Destructors are noexcept by default; an exception escaping one terminates the program.
  • An unnamed guard. MaintenanceWindow{catalog}; creates a temporary that is destroyed at the semicolon, so the guarded work is not covered. (With parentheses, MaintenanceWindow(catalog); is even parsed as declaring a new variable named catalog, which here fails to compile.) Always give the guard a name: MaintenanceWindow window(catalog);.

New requirement: “Reports must be written to a temporary file and only renamed to the final name if the whole report was written.”

With RAII, this is a small new class: a TemporaryFile that creates the temporary file in its constructor, offers commit() to rename it to the final name, and deletes the temporary file in its destructor if commit() was never called. write_report gains one call to commit() at its end. Every failure path, including exceptions, now deletes the half-written file automatically. With manual cleanup, each early return and each possible exception would need its own delete call.

Exercise: Convert manual cleanup to RAII

A catalog must be switched into maintenance mode while it is reindexed, and back afterwards. Here is the current code:

Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.

// Several paths leave this function, and only the last one remembers to
// call end_maintenance().
bool reindex(Catalog& catalog) {
catalog.begin_maintenance();
if (!rebuild_title_index(catalog)) return false; // stuck in maintenance
rebuild_author_index(catalog); // may throw: stuck again
catalog.end_maintenance();
return true;
}

The Catalog class is:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

maintenance.hpp
// A catalog that can be switched into "maintenance mode" and back. The
// flag is the resource here: whoever switches it on must switch it off.
class Catalog {
public:
void begin_maintenance() noexcept { in_maintenance_ = true; }
void end_maintenance() noexcept { in_maintenance_ = false; }
[[nodiscard]] bool in_maintenance() const noexcept { return in_maintenance_; }
private:
bool in_maintenance_ = false;
};
  1. Write an RAII class that guarantees end_maintenance() is called.
  2. Rewrite reindex to use it.
  3. Should the class be copyable? Why or why not?
Show the explained answer
  1. A scope guard that begins maintenance in its constructor and ends it in its destructor. It is compiled and tested with this page’s examples:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

maintenance.hpp
// Begins maintenance when constructed and ends it when destroyed, so no
// early return or exception can leave the catalog stuck in maintenance.
// A guard like this is called a scope guard. Give it a name when you
// create it, so that it lives until the end of the block.
class MaintenanceWindow {
public:
// Takes the catalog by reference (it cannot be null) and keeps its
// address, &catalog, in a pointer. `->` calls a member through a pointer.
explicit MaintenanceWindow(Catalog& catalog) : catalog_(&catalog) {
catalog_->begin_maintenance();
}
~MaintenanceWindow() { catalog_->end_maintenance(); }
// Not copyable: a copy would end maintenance a second time, and the
// first copy to be destroyed would end it while the other still ran.
MaintenanceWindow(const MaintenanceWindow&) = delete;
MaintenanceWindow& operator=(const MaintenanceWindow&) = delete;
private:
Catalog* catalog_; // non-owning, never null
};
  1. reindex no longer mentions ending maintenance:

IllustrativeA fragment for explanation; not compiled on its own.

bool reindex(Catalog& catalog) {
// Begins maintenance now; ~MaintenanceWindow ends it when `window` goes
// out of scope, on whichever path the function is left.
const MaintenanceWindow window(catalog);
if (!rebuild_title_index(catalog)) return false; // window ends maintenance
rebuild_author_index(catalog); // even if this throws
return true;
}
  1. No. A copy would call end_maintenance() a second time when it is destroyed. For a flag that is harmless, but it is wrong in principle (the maintenance would end when the first copy is destroyed, while the second still believes it is active), and for a real resource it would be a double release. Deleting the copy operations makes the mistake a compile error.

Notice also that MaintenanceWindow does not own the catalog. It observes it through a pointer (never null), and the catalog must outlive the guard, which is true whenever the guard is a local variable in a function that receives the catalog by reference.

  • A resource is anything acquired that must be released: memory, files, locks, connections, temporary state.
  • RAII acquires in a constructor and releases in the destructor, so release happens on every path out of a scope, including exceptions.
  • RAII classes must not be copyable unless copying the resource is meaningful.
  • Use standard RAII types where they exist; write your own for C handles and your own begin/end pairs.
  • Destructors must not throw; offer an explicit function when release can fail in a way callers must know about.