RAII - Resource Acquisition Is Initialization - is the most important idea in the language, and the name is unhelpfully abstract for something simple: tie a resource to the lifetime of an object. Acquire it in the constructor, release it in the destructor, and then the resource is released automatically when the object goes out of scope, on every path out of that scope, including the one taken by an exception.
Every modern C++ type you have met in this course is an application of it. std::vector frees its buffer. std::string frees its characters. std::unique_ptr deletes what it owns. std::lock_guard unlocks. std::ifstream closes. None of them need cleanup code because the type's destructor is the cleanup code, written once.
The practical rule: if you are writing delete, fclose, unlock or release yourself, you are writing a bug that has not happened yet. It takes one early return, one throw, one break added later by somebody who did not notice, and the cleanup is skipped. Wrap the resource in a type whose destructor releases it and the problem cannot occur.
Build systems. Beyond a handful of files, typing compiler commands stops working, and compiler commands are per-platform anyway. CMake is the de facto standard: you describe targets and their relationships in CMakeLists.txt, and CMake generates whatever the local toolchain uses - Makefiles, Ninja, or a Visual Studio solution. Prefer modern, target-based CMake: target_link_libraries, target_include_directories with PUBLIC and PRIVATE, and no global include_directories commands, because those leak settings into every target in the project.
Testing. C++'s two standard choices are GoogleTest and Catch2. GoogleTest is the more common in large codebases; Catch2 is header-only and quicker to start with. Either integrates with CMake through FetchContent, so a fresh clone needs no manual dependency installation. The habit that matters more than the framework: when you find a bug, write the failing test first, then fix it. That way you know the test actually detects the bug, and it stays in the suite to stop it coming back.
// ================= RAII: a type that owns a C resource =================
#include <cstdio>
#include <stdexcept>
#include <string>
#include <utility>
class File
{
public:
explicit File(const std::string& path, const char* mode = "r")
: handle_{std::fopen(path.c_str(), mode)}
{
if (handle_ == nullptr) {
throw std::runtime_error{"cannot open " + path};
}
}
~File() { if (handle_ != nullptr) { std::fclose(handle_); } }
// Owning types must say what copying means. This one is not
// copyable - two owners closing one handle is a double free.
File(const File&) = delete;
File& operator=(const File&) = delete;
// Movable, though: ownership transfers and the source is emptied.
File(File&& other) noexcept : handle_{std::exchange(other.handle_, nullptr)} {}
std::FILE* get() const { return handle_; }
private:
std::FILE* handle_;
};
bool looks_empty(const File& f); // declared elsewhere
void use(bool fail)
{
File f{"data.txt"}; // acquired here, in the constructor
if (looks_empty(f)) {
return; // closed on the way out
}
if (fail) {
throw std::runtime_error{"boom"};
} // closed on the way out
} // closed on the way out
// No fclose is written anywhere, and there is no path that forgets one.
// Add a fourth exit next year and it is still closed.
// ================= CMake: one build, three platforms =================
//
// CMakeLists.txt, at the project root:
//
// cmake_minimum_required(VERSION 3.20)
// project(demo LANGUAGES CXX)
//
// set(CMAKE_CXX_STANDARD 20)
// set(CMAKE_CXX_STANDARD_REQUIRED ON)
//
// # The library: the code worth testing.
// add_library(core src/file.cpp src/account.cpp)
// target_include_directories(core PUBLIC include)
// # ^^^^^^ PUBLIC: anything linking
// # core also gets this include path. PRIVATE would keep it to core.
// # Prefer these over the old global include_directories(), which
// # leaks settings into every target in the project.
//
// # The program: thin, so that almost everything is testable.
// add_executable(demo src/main.cpp)
// target_link_libraries(demo PRIVATE core)
//
// # Tests, fetched at configure time so a fresh clone just works.
// include(FetchContent)
// FetchContent_Declare(catch2
// GIT_REPOSITORY https://github.com/catchorg/Catch2.git
// GIT_TAG v3.5.2)
// FetchContent_MakeAvailable(catch2)
//
// enable_testing()
// add_executable(tests tests/file_test.cpp)
// target_link_libraries(tests PRIVATE core Catch2::Catch2WithMain)
//
// include(Catch)
// catch_discover_tests(tests)
//
// Then, on Linux, macOS or Windows, the same three commands:
//
// cmake -S . -B build
// cmake --build build
// ctest --test-dir build --output-on-failure
// ================= A test, with Catch2 =================
//
// tests/file_test.cpp:
//
// #include <catch2/catch_test_macros.hpp>
// #include "file.h"
//
// TEST_CASE("opening a missing file throws", "[file]")
// {
// REQUIRE_THROWS_AS(File{"no-such-file.txt"}, std::runtime_error);
// }
//
// TEST_CASE("a moved-from File no longer owns a handle", "[file]")
// {
// File a{"data.txt"};
// File b{std::move(a)};
//
// REQUIRE(b.get() != nullptr);
// REQUIRE(a.get() == nullptr); // emptied, and safe to destroy
// }
//
// The habit that matters more than the framework: when you find a bug,
// write the failing test FIRST and watch it fail. Then fix it. That way
// you know the test detects the bug, rather than hoping it would have.
Discussion
No questions on this topic yet. Sign in to ask the first one.