RAII (Resource Acquisition Is Initialization) — Explained with Examples
RAII (Resource Acquisition Is Initialization) is a C++ programming idiom where resources — memory, file handles, network sockets, mutex locks — are acquired during object construction and released during object destruction. Because C++ guarantees destructors run when objects go out of scope (even via exceptions), resources are automatically cleaned up.
RAII is the backbone of exception-safe C++ code. A std::vector acquires heap memory in its constructor and releases it in its destructor. A std::lock_guard acquires a mutex on construction and releases it on destruction — you cannot forget to unlock, even if an exception is thrown. Languages like Rust use a similar pattern (ownership and borrowing), while garbage-collected languages like Java and C# rely on the GC (Garbage Collection) or finally blocks for resource management.
Real-world analogy. RAII is like a hotel key card that grants access to your room (acquire) and automatically deactivates when you check out (release). You cannot accidentally leave the room unlocked — the key stops working. Contrast with a physical key: you might forget to return it at checkout.
Example (C++ — RAII with file and mutex):
#include <fstream>
#include <mutex>
void writeFile() {
std::ofstream file("log.txt"); // Acquire (opens file)
std::lock_guard<std::mutex> lock(mtx); // Acquire (locks mutex)
file << "Hello, RAII!\n";
// Auto-release: lock releases mutex, file closes
}Related terms: Garbage Collection, OOP, Destructor, Memory Safety, Ownership
Related tutorial: RAII in C++
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro