All Courses
OOP: RAII AND OWNERSHIP

RAII

Concept Definition

RAII means Resource Acquisition Is Initialization. The idea is simple: acquire a resource inside an object's construction path and release it inside the object's destruction path. When scope ends, cleanup happens automatically.

A useful analogy is borrowing a library key with an automatic return box. When your allowed time ends, the return process is built into the system instead of depending on memory or mood.

Why It Matters

Manual cleanup is fragile. If a function has three return paths or throws an exception, a hand-written delete, close, or unlock can be skipped. RAII makes cleanup part of object lifetime, so the compiler helps enforce it.

This is one of the most important differences between beginner C++ and professional C++. You stop asking "where should I remember to clean this?" and start asking "which object owns this resource?"

Syntax Block

class Owner {
public:
    Owner();   // acquire resource
    ~Owner();  // release resource
};

Explained Code

Example: File Resource Managed by RAII

#include <fstream>    // std::ofstream
#include <stdexcept>  // std::runtime_error
#include <string>     // std::string

class LogFile {
private:
    std::ofstream file;                         // owns the open file handle

public:
    explicit LogFile(const std::string& path) : file(path) { // open during construction
        if (!file) {                            // check acquisition result
            throw std::runtime_error("could not open file"); // fail early
        }
    }

    void write(const std::string& message) {
        file << message << '\n';                // use the owned resource
    }
};                                              // ofstream closes automatically

LogFile does not need a manual destructor because std::ofstream already follows RAII. When LogFile is destroyed, its member is destroyed too.

Key Points / Rules

  • Tie resource ownership to object lifetime.
  • Prefer standard library RAII types before writing your own destructor.
  • Construction should leave the object ready to use or throw an exception.
  • Destructors should release resources without requiring the caller to remember cleanup.
  • Scope becomes your cleanup boundary.

Common Mistakes

  1. Opening a resource without an owner. A raw file handle or raw pointer floating around the code has unclear cleanup.
  2. Writing a close() method and expecting callers to remember it. A manual close method can exist, but destruction should still be safe.
  3. Doing too much work in a destructor. Destructors should release resources, not run complicated business logic.
  4. Ignoring exception paths. RAII is valuable because exceptions still destroy local objects during stack unwinding.

Quick Check

  1. Why does LogFile not need to call file.close() explicitly?
  2. What resource does std::ofstream manage?

Viva Answer

RAII binds resource management to object lifetime. A constructor acquires or prepares the resource, and the destructor releases it automatically when the object leaves scope.