bhylu.com

Advertisements

C++ RAII

Observe deterministic destruction and tie a resource lifetime to one owning object.

How it works

RAII means acquiring a resource as part of an object’s initialization and releasing it in that object’s destructor. The owner then cleans up when its scope ends, including when an exception unwinds the scope. Standard strings, containers, streams and smart pointers already implement this pattern. Begin with those owners instead of writing manual new/delete pairs. The simple tracing type below shows the lifecycle without acquiring a real external resource, so every expected message can be explained.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror raii.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · raii.cpp

#include <iostream>

class TraceRound {
public:
    TraceRound() { std::cout << "Round opened\n"; }
    ~TraceRound() { std::cout << "Round closed\n"; }
};

int main() {
    std::cout << "Before scope\n";
    { TraceRound round; std::cout << "Inside scope\n"; }
    std::cout << "After scope\n";
}

Expected result

Before scope
Round opened
Inside scope
Round closed
After scope

Construction occurs before the inner body continues, and destruction occurs at the closing brace. Real resource destructors should not throw while cleanup is in progress. RAII does not by itself guarantee that an output file was successfully flushed; an API may need an explicit checked commit or close before the destructor’s fallback cleanup.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.