C++ · Module 11 · Lesson 11 min read

RAII in Depth

The RAII recipe

  1. Write a small class whose constructor acquires a resource
  2. Its destructor releases it
  3. Make it non-copyable (or define copying carefully) and usually movable
  4. Use it as a local variable — cleanup becomes automatic

Why RAII beats manual cleanup

scss
void transfer() {
    lock(m);
    if (!check()) return;      // ❌ forgot unlock
    do_work();                  // ❌ throws → never unlocks
    unlock(m);
}

With RAII:

arduino
void transfer() {
    std::lock_guard<std::mutex> guard(m);   // unlocks in every case ✅
    if (!check()) return;
    do_work();
}

Exception safety guarantees

GuaranteeMeaning
No-thrownever fails (noexcept)
Strongif it fails, nothing changed (commit or rollback)
Basicif it fails, no leaks, objects still valid
RAII makes at least the basic guarantee easy.

Scope guards

A generic RAII helper that runs any function at scope exit:

ini
auto cleanup = ScopeGuard([&] { remove_temp_file(); });

(A std::scope_exit is proposed for the standard; many libraries provide one.)

Transactions with RAII

Commit on success, rollback in the destructor unless commit() was called.

RAII wrappers for C APIs

c
std::unique_ptr<FILE, decltype(&std::fclose)> f(std::fopen("a.txt", "r"), &std::fclose);

A unique_ptr with a custom deleter turns any C handle into an RAII object (lesson 11.4).

Standard RAII types you already use

std::string, std::vector, std::fstream, std::unique_ptr, std::lock_guard, std::jthread

Example

C++
#include <functional>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

class ScopeGuard {                                   // runs an action when the scope ends
public:
    explicit ScopeGuard(std::function<void()> f) : f_(std::move(f)) {}
    ~ScopeGuard() { if (active_) f_(); }
    void dismiss() { active_ = false; }
    ScopeGuard(const ScopeGuard&) = delete;
    ScopeGuard& operator=(const ScopeGuard&) = delete;
private:
    std::function<void()> f_;
    bool active_ = true;
};

class Transaction {                                  // rollback unless committed
public:
    explicit Transaction(std::vector<double>& ledger) : ledger_(ledger), saved_(ledger) {
        std::cout << "  BEGIN\n";
    }
    ~Transaction() {
        if (!committed_) { ledger_ = saved_; std::cout << "  ROLLBACK\n"; }
    }
    void commit() { committed_ = true; std::cout << "  COMMIT\n"; }
    Transaction(const Transaction&) = delete;
    Transaction& operator=(const Transaction&) = delete;
private:
    std::vector<double>& ledger_;
    std::vector<double> saved_;
    bool committed_ = false;
};

void record_payment(std::vector<double>& ledger, double amount) {
    Transaction tx(ledger);
    ledger.push_back(-amount);                       // debit
    if (amount > 10000) throw std::runtime_error("limit exceeded");
    ledger.push_back(amount);                        // credit
    tx.commit();
}

int main() {
    {
        ScopeGuard g([] { std::cout << "temp file deleted\n"; });
        std::cout << "working with temp file...\n";
    }

    std::vector<double> ledger;
    std::cout << "Payment of 2500:\n";
    record_payment(ledger, 2500);
    std::cout << "Payment of 50000:\n";
    try {
        record_payment(ledger, 50000);
    } catch (const std::exception& e) {
        std::cout << "  error: " << e.what() << '\n';
    }
    std::cout << "ledger entries: " << ledger.size() << " (the failed payment left no trace)\n";

    ScopeGuard notify([] { std::cout << "this never prints\n"; });
    notify.dismiss();
    std::cout << "done\n";
    return 0;
}

/* Output:
working with temp file...
temp file deleted
Payment of 2500:
  BEGIN
  COMMIT
Payment of 50000:
  BEGIN
  ROLLBACK
  error: limit exceeded
ledger entries: 2 (the failed payment left no trace)
done
*/