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 automaticallyAll lessons in this course
- The RAII Principle
- Destructors and Cleanup
- Rule of Three/Five
- Scope Guards