RAII and Deterministic Cleanup
Tie resource lifetime to object lifetime.
What is RAII and Deterministic Cleanup?
Resource acquisition is initialization makes cleanup automatic on every scope exit, including exceptions.
Important points
- Understand the C mechanism before comparing the C++ abstraction.
- Use RAII and value semantics to express ownership.
- Prefer type-safe compile-time abstractions over macros and casts.
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
C uses a cleanup label so every exit path closes the file. C++ fstream closes in its destructor, making ownership local and reducing leak-prone control flow.
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.
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