RAII in C++ - Automatic Cleanup vs goto cleanup in C
Never forget to close a file again. RAII ties a resource to an object so cleanup runs on every exit path, even exceptions.
- Constructors acquire, destructors release
- Why early returns leak in C
- RAII types: fstream, unique_ptr, lock_guard
- 1
std::ofstream out(...)Constructor opens the file - 2
out << dataUse it - 3
return / throw / }Leave the scope any way - 4
~ofstream()Destructor closes the file
Resource lifetime equals object lifetime
The problem
Files, memory and locks must be released when you are done, on every path: normal end, early return, or error. Forgetting one path leaks the resource. C++ ties the release to an object, so it happens automatically.
Think of it like this
RAII is like a hotel key card that automatically stops working when you check out. You never have to remember to hand it in; leaving the hotel (the scope) ends the access, whatever route you take out.
fopen("scores.txt", "w")🗝️ C: get a key you must return yourselfgoto cleanup;🚪 C: every exit must pass the front deskstd::ofstream file("scores.txt");💳 C++: a card tied to your stayend of main🏁 Leaving the scope closes the file automaticallyRAII (Resource Acquisition Is Initialization) means an object acquires a resource in its constructor and releases it in its destructor. Cleanup then happens automatically when the object goes out of scope.
Important points
- In C, every failure jumps to
cleanup, wherefcloseruns iffilewas opened. resultstarts as 1 (failure) and becomes 0 only afterfputssucceeds.- In C++,
std::ofstreamopens the file in its constructor. - The file closes automatically when
filegoes out of scope at the end ofmain.
When to use it
- Files, sockets and database connections.
- Memory with
std::unique_ptrand containers. - Locks with
std::lock_guard, so a mutex is always released.
When not to use it
- C code: there are no destructors, so use a single cleanup path instead.
- Resources that must outlive the scope: move ownership to an object that lives longer.
C and C++ code examples
#include <stdio.h>
int main(void) {
int result = 1;
FILE *file = fopen("scores.txt", "w");
if (!file) goto cleanup;
if (fputs("Ada 95\n", file) < 0) goto cleanup;
result = 0;
cleanup:
if (file) fclose(file);
puts(result ? "failed" : "saved");
return result;
}
saved
#include <fstream>
#include <iostream>
int main() {
std::ofstream file("scores.txt");
if (!file) return 1;
file << "Ada 95\n";
std::cout << "saved\n";
}
saved
C and C++ comparison
The C version jumps to one cleanup label from every failure, so fclose runs on all paths and result reports success or failure. In C++, std::ofstream opens the file when it is created and closes it in its destructor. Leaving main by any path closes the file without extra code.
C uses naming conventions, callbacks, macros, and explicit context structures.
Language features provide scoped, type-safe, and often zero-overhead abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Write the C mechanism before the C++ abstraction.
- Remove manual cleanup with RAII.
- Check whether the abstraction adds allocations or virtual dispatch.
Common mistakes
Missing cleanup on an early return
Returning before fclose leaks the file handle.
if (fputs("Ada 95\n", file) < 0) return 1;
if (fputs("Ada 95\n", file) < 0) goto cleanup;
Manual new and delete in C++
An exception between them leaks the memory.
int *data = new int[100];
// ...
delete[] data;
std::vector<int> data(100);
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges