Modern C++ • C++20 baseline
RAII and Deterministic Resource Management
Use object lifetime to manage files, locks, memory, and other resources.
RAII means acquiring a resource as part of object construction and releasing it during destruction. This gives cleanup a reliable path through early returns and exceptions. Prefer standard RAII types such as std::vector, std::unique_ptr, std::fstream, and std::lock_guard instead of manually pairing acquire and release calls.
Key points
- Every owning resource should have one clear owner.
- Avoid raw new/delete in application code when a standard owner can express the same lifetime.
Example
#include <fstream>
#include <stdexcept>
#include <string>
std::string first_line(const std::string& path) {
std::ifstream input(path);
if (!input) {
throw std::runtime_error("could not open input file");
}
std::string line;
std::getline(input, line);
return line;
}
What to expect
The file closes automatically when the stream leaves scope, including if reading throws.
Practice exercise
Add a second operation after opening the file that can fail. Verify there is no manual cleanup branch to forget.
Key idea: Prefer deterministic cleanup through RAII to scattered cleanup code.