Resource Acquisition Is Initialization (RAII)
Resource usage is usually as follows:
- Optain
- Use
- Release
Rule: Who owns the resource also deallocates it
A RAII class:
- Allocates resources in the constructor
- Deallocates resources in the ~destructor
- All instances of a RAII class are allocated on the stack
Without RAII
double den[] = {1.0, 2.0, 3.0, 4.0, 5.0};
for (size_t i = 0; i < 5; i++) {
double *en = new double(i);
std::cout << *en << "/" << den[i] << " = " << *en / den[i] << std::endl;
// Easy to forget:
delete en;
}
With RAII
double den[] = {1.0, 2.0, 3.0, 4.0, 5.0};
for (size_t i = 0; i < 5; i++) {
// Good: Allocated on the STACK
MyInt en(new int(i));
// Bad: Allocated on the HEAP
// MyInt *en = new MyInt(new int(i));
std::cout << *en << "/" << den[i] << " = " << *en / den[i] << std::endl;
}
class MyInt {
public:
MyInt(int *p = nullptr) { p_ = p; }
~MyInt() {
delete p_;
}
private:
int *p_;
}