On this page
  1. RAII, Smart Pointers & Lifetime
  2. Overview
  3. Parameter-Passing Conventions (Ownership in Signatures)
  4. Common Lifetime Hazards
  5. Catching Lifetime Bugs with Sanitizers

RAII, Smart Pointers & Lifetime

Prev: Value Categories & Move Semantics | Up: Language & RAII | Next: Templates, Concepts & Polymorphism
Rel: RAII & Destructors, C++ `<memory>`, std::string_view, std::span, Memory Management Models
Ref: ISO C++ Core Guidelines — Resource Management
Tags: #public #prog #cpp #raii #memory #tier/core


Overview

Modern C++ achieves deterministic memory and resource safety without a garbage collector by encoding ownership directly in types and scoping every allocation to an RAII handle.

Parameter-Passing Conventions (Ownership in Signatures)

Parameter Type Ownership Meaning
const T& / T& Non-owning borrow (must not be null)
std::string_view / std::span<const T> Non-owning read-only slice (pass by value)
T* / const T* Non-owning optional borrow (may be nullptr)
std::unique_ptr<T> (by value) Transfers exclusive ownership into the function (sink)
std::shared_ptr<T> (by value) Function shares ownership and extends the object's lifetime

Never take const std::unique_ptr<T>& just to read the pointee—accept const T& or const T* so the function works regardless of how the caller manages memory.

Common Lifetime Hazards

  1. Dangling views (std::string_view, std::span):
    // BUG: temporary std::string dies at the semicolon!
    std::string_view bad = std::string("hello") + " world";
    
  2. Iterator/reference invalidation: Calling vec.push_back(...) may reallocate and invalidate every pointer, reference, and std::span pointing into vec.
  3. Lambda [&] escaping scope: Passing a [&] lambda to a thread or callback that outlives the local stack frame causes use-after-return.

Catching Lifetime Bugs with Sanitizers

Always run your test suite with AddressSanitizer and UndefinedBehaviorSanitizer enabled in debug/CI builds:

clang++ -std=c++23 -O1 -g -fsanitize=address,undefined -Wall -Wextra -Wpedantic main.cpp -o app

Linked from

Related notes