LOGBOOK

HELP

Quiz Entry - updated: 2026.07.06

What is RAII in C++?

RAII = Resource Acquisition Is Initialization: tie a resource's lifetime to an object so its destructor releases the resource automatically.

Constructor acquires the resource, the object is used, the destructor releases it at scope exit

* The constructor acquires, the destructor releases — and because the destructor runs at every scope exit (even during an exception), cleanup can't be forgotten. *

void process() {
    vector<int> v;        // memory acquired
    v.push_back(1);
    // ... use v ...
}   // v goes out of scope -> destructor frees its memory automatically

void readFile() {
    ifstream file("data.txt");   // file opened
    // ... read from file ...
}   // file closed automatically when it's destroyed

Key principle:

  • Acquire the resource in the constructor
  • Release it in the destructor
  • The object's scope then controls the resource's lifetime

Benefits:

  • No leaks — cleanup is automatic, even if you forget
  • Exception-safe — destructors still run as the stack unwinds during an exception
  • No scattered manual cleanup code

Tip: RAII is why smart pointers (unique_ptr, shared_ptr) are preferred over raw new/delete — they're RAII wrappers that delete for you.

Go deeper:

From Quiz: REVE1 / C++ Programming | Updated: Jul 06, 2026