RAII and Resource Management
Tie every resource to the lifetime of an object
- explain what a resource is and why leaks happen,
- bind a resource to an object with a constructor and destructor,
- apply the Rule of Three and the Rule of Five,
- reach for the Rule of Zero with smart pointers and containers.
1. What is a resource, and why do leaks happen?
A resource is anything your program borrows from the system and must eventually give back: heap memory from new, an open file handle, a network socket, a database connection, a mutex lock. The pattern is always the same: acquire, use, then release. Forget to release, and you have a leak — the resource stays reserved even though nobody is using it.
Manual cleanup looks easy until real code gets in the way:
void process() {
int* data = new int[1000]; // acquire
if (!load(data)) {
return; // LEAK: we forgot delete[] on this path
}
compute(data);
delete[] data; // release (only on the happy path)
}
The early return skips delete[]. Worse, if compute() throws an exception, the delete[] line is never reached at all. Every branch, every exception, every future edit is a chance to leak. RAII removes the human from the loop.