RAII and Deterministic Cleanup
Resource acquisition is initialization makes cleanup automatic on every scope exit, including exceptions.
What is RAII and Deterministic Cleanup?
Resource acquisition is initialization makes cleanup automatic on every scope exit, including exceptions.
Tie resource lifetime to object lifetime.
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
main.c
#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
C++
main.cpp
#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
C uses naming conventions, callbacks, macros, and explicit context structures.
C++
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.