Skip to content

Search topics & cppreference

Search all study topics, concept maps, and 6,587 C++ and C reference pages.

RAII

Separate raw memory allocation from object existence, master scope-bound RAII, and dodge dangling temporary traps.

Language
  • C++11
  • C++20
2 min readView on cppreference
NotebookLM
[basic.life][basic.stc][class.temporary][stmt.ranged]

Allocating bytes does not create an object, and freeing bytes is not what destroys one—lifetime begins at initialization and ends at destruction or storage reuse.

CppCon angle
Show the two timelines side by side: storage duration (how long the bytes exist) vs. object lifetime (when the typed object is legally alive inside those bytes).
Common audience trap
Assuming temporary lifetime extension propagates through accessor methods like auto& x = make_container().front(); inside range-for loops.
Stage takeaway
Use C++20 std::bit_cast instead of pointer-punning reinterpret_cast, and verify C++23 P2718 before trusting chained temporaries in range-for.

Storage duration is not object lifetime

[basic.life] §6.7.3

When you allocate raw aligned storage (alignas(Widget) std::byte buf[sizeof(Widget)];), storage exists, yet zero Widget objects live there. Accessing a Widget* pointing to buf before placement-new construction is Undefined Behavior.

C++20 softened one long-standing C interop pain point with Implicit-Lifetime Types ([intro.object]): malloc or std::start_lifetime_as (C++23) can implicitly begin the lifetime of trivial aggregates/arrays so C network buffers no longer rely on theoretical UB.

Why std::launder exists for const members
struct Node { const int id; };
Node* p = new Node{1};
// Reuse p's storage with placement new:
new (p) Node{2};
// Compiler may legally assume p->id is STILL 1 because 'id' is const!
int safe_id = std::launder(p)->id; // Guaranteed 2 ([ptr.launder])

Key rule: Compilers track pointer provenance and const member immutability; std::launder tells the optimizer a fresh object replaced the old one at that address.

Temporary lifetime extension & the range-for cliff

[class.temporary] & [stmt.ranged]

Writing const std::string& s = make_name(); extends the materialized temporary string to match s's scope. Write const char* p = make_name().c_str(); or auto& item : get_wrapper().items() in C++11–C++20, and the outer temporary wrapper is destroyed BEFORE the loop body even begins!

C++23 paper P2718R0 finally fixed range-based for loops by extending the lifetime of ALL temporaries in the range-initializer expression until the loop finishes—matching what every developer already assumed.

Pre-C++23 range-for dangling temporary
struct Wrapper { std::vector<int> items{1, 2, 3}; };
Wrapper make_wrapper();

// Pre-C++23: UB! Wrapper temporary dies before loop starts!
// C++23 (P2718R0): Well-defined! All temporaries in range-init extend across loop.
for (int v : make_wrapper().items) {
    use(v);
}

Key rule: Whenever a function returns a reference or view into a temporary receiver (std::string_view, std::span, or .items), check whether you are pre-C++23.

Across revisions (C++11 → C++17 → C++20 → C++23)

C++17

Introduced std::launder in <new> for placement-new over objects with const/reference members.

C++20

Introduced Implicit-Lifetime Types ([intro.object]) and std::bit_cast<To>(from) to eliminate strict-aliasing UB.

C++23

P2718R0 extended lifetime of all temporaries inside range-based for initializers; added std::start_lifetime_as.

Full 1:1 cppreference specification

Original specification mirrored from cppreference.com with restyled declaration panels and code windows.

Resource Acquisition Is Initialization or RAII, is a C++ programming technique[1][2] which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the lifetime of an object.

RAII guarantees that the resource is available to any function that may access the object (resource availability is a class invariant, eliminating redundant runtime tests). It also guarantees that all resources are released when the lifetime of their controlling object ends, in reverse order of acquisition. Likewise, if resource acquisition fails (the constructor exits with an exception), all resources acquired by every fully-constructed member and base subobject are released in reverse order of initialization. This leverages the core language features (object lifetime, scope exit, order of initialization and stack unwinding) to eliminate resource leaks and guarantee exception safety. Another name for this technique is Scope-Bound Resource Management (SBRM), after the basic use case where the lifetime of an RAII object ends due to scope exit.

RAII can be summarized as follows:

  • encapsulate each resource into a class, where
  • the constructor acquires the resource and establishes all class invariants or throws an exception if that cannot be done,
  • the destructor releases the resource and never throws exceptions;
  • always use the resource via an instance of a RAII-class that either
  • has automatic storage duration or temporary lifetime itself, or
  • has lifetime that is bounded by the lifetime of an automatic or temporary object.

Move semantics enable the transfer of resources and ownership between objects, inside and outside containers, and across threads, while ensuring resource safety.

(since C++11)

Classes with open()/close(), lock()/unlock(), or init()/copyFrom()/destroy() member functions are typical examples of non-RAII classes:

snippet.cpp
std::mutex m;
 
void bad() 
{
    m.lock();             // acquire the mutex
    f();                  // if f() throws an exception, the mutex is never released
    if (!everything_ok())
        return;           // early return, the mutex is never released
    m.unlock();           // if bad() reaches this statement, the mutex is released
}
 
void good()
{
    std::lock_guard<std::mutex> lk(m); // RAII class: mutex acquisition is initialization
    f();                               // if f() throws an exception, the mutex is released
    if (!everything_ok())
        return;                        // early return, the mutex is released
}                                      // if good() returns normally, the mutex is released

The standard library

The C++ library classes that manage their own resources follow RAII: std::string, std::vector, std::jthread(since C++20), and many others acquire their resources in constructors (which throw exceptions on errors), release them in their destructors (which never throw), and don't require explicit cleanup.

In addition, the standard library offers several RAII wrappers to manage user-provided resources:

(since C++11)

Notes

RAII does not apply to the management of the resources that are not acquired before use: CPU time, core availability, cache capacity, entropy pool capacity, network bandwidth, electric power consumption, stack memory. For such resources, a C++ class constructor cannot guarantee resource availability for the duration of object lifetime, and other means of resource management have to be used.

  1. ↑ RAII in Stroustrup's C++ FAQ
  2. ↑ C++ Core Guidelines E.6 "Use RAII to prevent leaks"

Content from this page on cppreference.com, licensed under CC-BY-SA 3.0 and GFDL. Modified: restyled, site navigation removed, code windows added. Offline snapshot of 9 February 2025.