0Pricing
C++ Academy · Lesson

The RAII Principle

Tie resources to object lifetime.

What RAII Means

RAII stands for Resource Acquisition Is Initialization. A resource is acquired in a constructor and released in the destructor, tying its lifetime to an object.

The Core Idea

Wrap every resource — memory, files, locks, sockets — in an object. When the object goes out of scope, its destructor frees the resource automatically.

#include <iostream>

class Resource {
public:
    Resource() { std::cout << "acquire\n"; }
    ~Resource() { std::cout << "release\n"; }
};

int main() {
    Resource r;   // acquired
}                 // released automatically

All lessons in this course

  1. The RAII Principle
  2. Destructors and Cleanup
  3. Rule of Three/Five
  4. Scope Guards
← Back to C++ Academy