singularity

🔑 RAII = Resource Acquisition Is Initialization

The idea: own a resource inside an object, and let the object’s lifetime manage the resource’s lifetime.

âś… What RAII actually means

⚠️ Where reference counting comes in

đźš« Garbage collection vs RAII

So the essence is:

RAII turns “manual alloc/free” into “automatic acquire/release at scope exit”, without a collector.

example w/file

#include <fstream>

void processFile(const std::string& path) {
    std::ifstream file(path); // opens in ctor
    if (!file) throw std::runtime_error("cannot open");

    std::string line;
    while (std::getline(file, line)) {
        // process...
    }
} // file goes out of scope -> destructor closes file

Mutex example

#include <mutex>

std::mutex m;

void criticalSection() {
    std::lock_guard<std::mutex> guard(m); // locks in ctor
    // safe work
} // guard dtor unlocks