RAII is a C++ programming idiom where resources (like memory, file handles, locks, sockets) are tied to the lifetime of objects.
The resource is:
So when an object goes out of scope, its destructor is automatically called, releasing the resource.
// MyClass.h
class MyClassImpl; // Forward declaration
class MyClass {
public:
MyClass();
~MyClass();
void doSomething();
private:
MyClassImpl* impl; // Pointer to implementation
};
// MyClass.cpp
#include "MyClass.h"
class MyClassImpl {
public:
void doSomethingImpl() {
std::cout << "Doing real work...\\n";
}
};
MyClass::MyClass() : impl(new MyClassImpl) {}
MyClass::~MyClass() { delete impl; }
void MyClass::doSomething() {
impl->doSomethingImpl();
}
| Feature | Purpose |
|---|---|
| Forward Declaration | Avoids including the full definition of MyClassImpl in header |
| Private Pointer | Actual implementation is hidden from users of the class |
| Dynamic Allocation | Impl object is created in .cpp file, not exposed outside |
| Use Case | Description |
|---|---|
| Library design | You can change implementation without recompiling users |
| Reducing build times | Prevents cascading recompilation on internal changes |
| Encapsulation | Completely hides private data and types from public headers |
| Stable APIs | ABI doesn’t change when internal members change |