01 / 21

RAII
Resource Acquisition Is Initialization

Master the C++ idiom that ties resource lifetime to object lifetime, eliminating leaks and making code exception-safe by design.

C++

What Is a Resource?

In programming, a resource is anything your program borrows from the operating system and must eventually give back. If you forget to return it, you create a leak: the system slowly runs out of that resource.

Heap Memory
Allocated with new, freed with delete
File Handles
Opened with fopen, closed with fclose
Network Sockets
Connected with connect, closed with close

The Manual Management Problem

When programmers manage resources by hand, three things go wrong: they forget to release, they release too early, or an exception skips the release code entirely.

Manual Approach new / allocate use resource delete / close? Easy to forget! exception! RAII Approach constructor (acquires resource) use resource destructor (releases resource) Automatic & safe!

Defining RAII

RAII stands for Resource Acquisition Is Initialization. It is a C++ design idiom where you tie the lifetime of a resource to the lifetime of an object:

1
Constructor acquires the resource (memory, file, lock, socket).
2
Object lifetime = resource lifetime. You use the resource through the object.
3
Destructor releases the resource: automatically called when the object goes out of scope.

Scope and Object Lifetime

In C++, every local variable lives inside a scope (a pair of curly braces). When execution exits that scope, every object declared inside it is destroyed in reverse order.

scope { } time FileGuard f("data.txt"); constructor: opens file f.write("hello"); f.read(); } // scope ends destructor: closes file lifetime

The Core RAII Principle

Constructor acquires resource (or throws) Object owns resource Destructor releases resource (guaranteed) RESOURCE LIFETIME = OBJECT LIFETIME

This principle eliminates the entire category of resource-leak bugs. If the object exists, the resource is valid. If the object is gone, the resource is freed.

Why RAII Is Exception-Safe

When an exception is thrown, C++ performs stack unwinding: it destroys every local object in reverse order as it exits each scope. RAII objects release their resources during this process.

Lock guard created File guard created EXCEPTION THROWN! stack unwinding ~FileGuard: close file ~LockGuard: unlock All resources freed, even during exceptions!

Raw vs Smart Pointers

The most common RAII wrappers in modern C++ are smart pointers. They replace raw new/delete calls with objects that automatically manage heap memory.

Raw Pointer Smart Pointer (RAII)
Allocation int* p = new int(42); auto p = make_unique<int>(42);
Cleanup Manual: delete p; Automatic: destructor
Exception-safe? No Yes
Leak risk High Zero

How to Apply RAII

1
Identify the resource: heap memory, file handle, mutex lock, database connection, etc.
2
Wrap it in a class: the constructor acquires (opens, allocates, locks). If acquisition fails, throw an exception.
3
Write the destructor: it releases (closes, deallocates, unlocks). Destructors must never throw.
4
Use the object on the stack: declare it as a local variable. Scope exit triggers cleanup.
5
Prefer standard library types: use unique_ptr, shared_ptr, lock_guard, fstream before writing your own.

Example 1: A Simple RAII Wrapper

class FileGuard { FILE* file_; public: // Constructor: acquires the resource FileGuard(const char* path) { file_ = fopen(path, "r"); if (!file_) throw std::runtime_error("open failed"); } // Destructor: releases the resource ~FileGuard() { if (file_) fclose(file_); } FILE* get() { return file_; } };

Example 2: std::unique_ptr

The standard library already provides RAII wrappers. std::unique_ptr is the most common: it exclusively owns a heap object and deletes it when destroyed.

#include <memory> void process() { // RAII: unique_ptr acquires heap memory auto data = std::make_unique<int[]>(1000); data[0] = 42; doWork(data.get()); // If doWork() throws, data is STILL freed! } // unique_ptr destructor calls delete[] here
unique_ptr
Single owner. Cannot be copied, only moved. Zero overhead.
shared_ptr
Multiple owners. Reference-counted. Freed when last owner dies.

Example 3: std::lock_guard

RAII isn't just for memory. A lock_guard acquires a mutex lock in its constructor and releases it in its destructor: no chance of forgetting to unlock.

#include <mutex> std::mutex mtx; int sharedCounter = 0; void increment() { // RAII: lock_guard locks the mutex std::lock_guard<std::mutex> guard(mtx); sharedCounter++; // Even if ++ throws, mutex is unlocked } // guard destructor unlocks mtx here

RAII in the Standard Library

You don't need to write your own RAII classes for most situations. The C++ standard library is built on RAII:

std::string
Manages its own character buffer on the heap
std::vector
Dynamic array: allocates and frees automatically
std::fstream
Opens file in constructor, closes in destructor
std::thread
Manages OS thread lifecycle via join/detach

The Rule of Five (and Zero)

When writing your own RAII class, you must consider copying and moving. If you define a destructor, you likely need all five special member functions:

1
Destructor: releases the resource
2
Copy constructor: deep-copy or disable
3
Copy assignment: deep-copy or disable
4
Move constructor: transfer ownership cheaply
5
Move assignment: transfer ownership cheaply

Common Mistakes with RAII

Naked new/delete
Using raw new and delete instead of smart pointers. One missed delete = memory leak.
Throwing in Destructors
If a destructor throws during stack unwinding, the program terminates. Destructors must be noexcept.
Shallow Copy
Copying an RAII object without a proper copy constructor: two objects try to free the same resource (double-free).

RAII vs Other Approaches

RAII (C++) Garbage Collection (Java) Manual (C)
Memory cleanup Deterministic Non-deterministic Manual
Non-memory resources Automatic Manual (try-finally) Manual
Exception safety Built-in Partial None
Runtime cost Zero GC pauses Zero
Leak risk Very low Memory: low, files: high High

Question 1 of 5

In RAII, when is a resource released?

Question 2 of 5

Which standard library type is an RAII wrapper for exclusive ownership of heap memory?

Question 3 of 5

Why must an RAII destructor never throw an exception?

Question 4 of 5

What is the "Rule of Zero"?

Question 5 of 5

Consider this code. What happens if doWork() throws an exception?