← Back to list

Mastering RAII (Resource Acquisition Is Initialization) in C++

RAII (Resource Acquisition Is Initialization) is a fundamental and powerful C++ programming idiom where resource allocation is tied to…

Saurabh Rajvaidya · 2025-07-02 13:44 · 6 claps · 2.3 min read
#cplusplus #raii #c-plus-plus-language #exception-handling
Open on Medium ↗
Wiki topics: 💻 · Programming

Mastering RAII (Resource Acquisition Is Initialization) in C++

Photo by Oyemike Princewill on Unsplash

Photo by Oyemike Princewill on Unsplash

RAII (Resource Acquisition Is Initialization) is a fundamental and powerful C++ programming idiom where resource allocation is tied to object lifetime. In simple terms:

A resource (e.g., memory, file, network connections, mutex, database connections) is acquired when an object is created (initialized), and automatically released when the object goes out of scope (destroyed).

[embed]

I have created a generic wrapper class to show how to use RAII concept and acquiring the managed/heap object in the class’s constructor at line 13 and releasing the object in destructor at line 22 and setting the m_ptr to nullptr at line 23 explicitly to avoid double deletion. The stack is a fixed-size memory region used for storing local variables like obj1 and obj2. The compiler handles both the allocation and deallocation of these variables automatically, ensuring they are released as soon as they leave scope.

We can not only bind memory resource but different resources as well. let’s see few examples

// Example-1
class FileHandler {
    std::ofstream file;
public:
    // Resource File is acquired here
    FileHandler(const std::string& filename) {
        file.open(filename);
        if (file.is_open()) {
            std::cout << "File opened\n";
        } else {
            throw std::runtime_error("Failed to open file");
        }
    }
    // Resource File is released here 
    ~FileHandler() {
        if (file.is_open()) {
            file.close();
            std::cout << "File closed\n";
        }
    }
};
// Example-2
class lock_guard {
    std::mutex& m_mutex;

public:
    // Resource Mutex is acquired here
    explicit lock_guard(std::mutex& mutex) : m_mutex(mutex) {
        std::cout << "Lock acquired\n";
        m_mutex.lock();
    }

    // Resource Mutex is released here
    ~lock_guard() {
        m_mutex.unlock();
        std::cout << "Lock released\n";
    }
};
// Example-3
class SocketWrapper {
    int sockfd;

public:
    // Resource Socket is acquired here
    SocketWrapper() {
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) {
            throw std::runtime_error("Failed to create socket");
        }
        std::cout << "Socket created: " << sockfd << "\n";
    }

    // Resource Socket is released here
    ~SocketWrapper() {
        if (sockfd >= 0) {
            close(sockfd);
            std::cout << "Socket closed: " << sockfd << "\n";
        }
    }
};
// Example-4
class SQLiteDB {
    sqlite3* db;

public:
    // Resource Database is acquired here
    SQLiteDB(const std::string& dbName) : db(nullptr) {
        if (sqlite3_open(dbName.c_str(), &db) != SQLITE_OK) {
            throw std::runtime_error("Failed to open database: " + std::string(sqlite3_errmsg(db)));
        }
        std::cout << "Opened database: " << dbName << "\n";
    }

    // Resource Database is released here
    ~SQLiteDB() {
        if (db) {
            sqlite3_close(db);
            std::cout << "Database closed\n";
        }
    }
};

Advantages of RAII:

  • Automatic resource cleanup — No need to remember to manually release resources
  • Exception safety — Ensures that resources are cleaned up even when exceptions are thrown
  • Simpler, cleaner code — Avoids clutter with try/catch patterns
  • Encapsulation of resource logic — Keeps resource acquisition and release logic inside a class
  • Prevents leaks and dangling resources — Reduces risk of bugs like memory leaks, file descriptor leaks, etc.

“Once you stop learning, you start dying — and so does your potential.”Albert Einstein

Feel free to share your feedback- your suggestions will help me improve both this blog and its content.


메타데이터
post_id
7e8d3dbcc20b
slug
mastering-raii-resource-acquisition-is-initialization-in-c-7e8d3dbcc20b
url
https://medium.com/@saurabh.professionalwork/mastering-raii-resource-acquisition-is-initialization-in-c-7e8d3dbcc20b
canonical_url
https://medium.com/@saurabh.professionalwork/mastering-raii-resource-acquisition-is-initialization-in-c-7e8d3dbcc20b
author_url
https://medium.com/@saurabh.professionalwork
status
ok
fetched_at
2026-07-19 04:46:19