What is RAII in C++?

RAII (Resource Acquisition Is Initialization) ties the life of a resource (memory, file, lock, socket) to the life of an object. The constructor takes the resource, and the destructor releases it. When the object leaves its scope, C++ calls the destructor, even if an exception is thrown.

#include <iostream>
#include <mutex>
#include <stdexcept>

std::mutex m;

void risky() {
    std::lock_guard<std::mutex> lock(m);        // RAII: locks here
    std::cout << "locked\n";
    throw std::runtime_error("oops");           // the lock is still released
}

int main() {
    try {
        risky();
    } catch (const std::exception& e) {
        std::cout << "caught: " << e.what() << '\n';
    }
    std::cout << "can lock again: " << m.try_lock() << '\n';
}
Output

locked
caught: oops
can lock again: 1

Standard RAII types: std::unique_ptr, std::vector, std::string, std::lock_guard and std::ofstream. See Constructors and Destructors.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.