Skip to main content

RAII

Resource Acquisition Is Initialization

RAII is a design pattern where resource lifetime is bound to object lifetime. When the object is created, it acquires the resource. When the object is destroyed, it releases the resource automatically via the destructor.

Resources Include : 

    heap memory file handles sockets mutex locks db connections GPU buffers threads
    File I/O RAII Example
    #include <iostream>
    #include <fstream>
    #include <string>
    
    // ifstream abides by RAII design pattern
    // Resource (file) is acquired during scope
    // Destructor naturally runs when escaping scope
    int main() {
      std::ifstream file{"file.txt"};
      if (file.isOpen()) {
        std::cout << "file is open" << std::endl;
      } else {
        std::cout << "file is close" << std::endl;
      }  
    }
    Mutex RAII Example
    std::mutex m;
    
    // No RAII object.
    // if some condition is true, m.unlock never runs -> deadlock
    void foo() {
      m.lock();
    
      if (some condition) {
        return;
      }
    
      m.unlock();
    }
    
    // With RAII object
    // destructor runs when leaving scope
    void bar() {
      std::lock_guard<std::mutex> lock(m);
    
      if (some condition) return;
    }