# C++ Atlas — Complete Study Guide

> 115 C++ deep-dive topics across 13 tracks with concept maps and standard-lawyer quizzes.

Source: C++ Atlas (https://cppatlas.com)

## Contents

- **Program structure**: Translation Units, ODR, and Linkage, The one-definition rule, Name Lookup, Qualified Lookup, and ADL, Namespaces and scope, C++20 Modules, The preprocessor and translation phases, Attributes, Program startup and termination
- **Types and initialization**: Fundamental types and arithmetic conversions, Implicit conversions, Casts and cv-qualifiers, Casts, const, volatile and qualifiers, Initialization Forms in C++, Aggregates and designated initializers, Type Deduction: auto, decltype, and CTAD, Enumerations and unions
- **Value semantics**: Value categories, Copy and move semantics, Copy elision and NRVO, Reference binding and temporaries
- **Expressions and functions**: Evaluation Order, Sequencing & Undefined Side Effects, Constant Expressions: constexpr, consteval & constinit, Lambdas: Closure Types, Captures & Generic Parameters, Overload Resolution: Candidates, Viability & Ranking, Operator overloading, Three-way comparison, Function parameters and default arguments, Structured bindings
- **Classes**: Member functions and this, Constructors & Member Initialization Order, Inheritance and Virtual Functions, Multiple and virtual inheritance, Access control and friends, Conversion functions and explicit, Pointers to members, RAII and Resource Management
- **Templates**: Template instantiation and specialization, Template argument deduction, Dependent names and two-phase lookup, Variadic templates and fold expressions, SFINAE and Concepts, SFINAE, Concepts and constraints, Forwarding References and Perfect Forwarding, Class template argument deduction, Type traits and metaprogramming, CRTP and Deducing This, Non-type template parameters, Partial ordering of templates
- **Exceptions and error handling**: Exceptions and stack unwinding, noexcept, Exception-safety guarantees, Optional, expected, and error codes
- **Memory model**: Object lifetime and storage, Object layout and alignment, Strict aliasing and undefined behavior, Strict aliasing and undefined behavior, Atomics and memory ordering, Dynamic allocation with new and delete, Smart pointers, control blocks, and allocators, Smart pointers, Allocators and polymorphic memory resources, Pointers, arrays and pointer arithmetic
- **Concurrency**: Threads, jthread, cooperative stop, and locks, Threads and jthread, Mutexes and locks, Condition variables and waiting, Futures, promises and async, C++20 coroutines and C++23 std::generator, Coroutine library and generators, Lock-free programming and ABA, Parallel algorithms and execution policies
- **Containers and strings**: Containers, memory layouts, and iterator invalidation, Sequence containers, Associative and unordered containers, Iterator invalidation, Container adaptors and flat containers, Strings, string_view, and span, Strings and string_view, span and mdspan, Node handles and heterogeneous lookup, array, bitset and vector<bool>
- **Iterators, algorithms and ranges**: Iterator categories and concepts, The algorithm library, Ranges, views, and niebloids, Ranges and views, Borrowed ranges and dangling, Range adaptors and pipelines, Strict weak ordering and comparators, Customization points and niebloids, Iterator adaptors and sentinels
- **Library utilities**: Vocabulary types and std::format, optional, variant and any, pair, tuple and the tuple protocol, Callable wrappers, chrono, std::format and std::print, Iostreams, std::filesystem, Random numbers, Floating point and numerics, Bit manipulation, Character types and Unicode, Integer arithmetic and overflow
- **C++26**: C++26: Contracts, Reflection, Execution, and Erroneous Behavior, Contracts, Static reflection, Senders and receivers (std::execution), std::simd data-parallel types, Erroneous behaviour and C++26 language changes, Pack indexing and C++26 template features, inplace_vector and the new C++26 containers, Hazard pointers and RCU, constexpr in C++26

---

# Track: Program structure

How source text becomes an executable: translation units, linkage, name lookup and modules.

# Translation Units, ODR, and Linkage

> Trace how source files become translation units and how scope, storage duration, linkage, and the One Definition Rule govern symbol visibility across them.

- **Source:** C++ Atlas (https://cppatlas.com/topics/translation-units-and-linkage)
- **Track:** Program structure
- **Estimated reading time:** 8 minutes
- **ISO C++ clauses:** [lex.phases] (https://eel.is/c++draft/lex.phases), [basic.scope] (https://eel.is/c++draft/basic.scope), [basic.stc] (https://eel.is/c++draft/basic.stc), [basic.link] (https://eel.is/c++draft/basic.link), [basic.def.odr] (https://eel.is/c++draft/basic.def.odr), [dcl.link] (https://eel.is/c++draft/dcl.link)
- **cppreference links:** [Phases of translation](https://en.cppreference.com/w/cpp/language/translation_phases), [Storage class specifiers](https://en.cppreference.com/w/cpp/language/storage_duration), [Definitions and ODR](https://en.cppreference.com/w/cpp/language/definition), [inline specifier](https://en.cppreference.com/w/cpp/language/inline), [Language linkage](https://en.cppreference.com/w/cpp/language/language_linkage), [Translation-unit-local entities](https://en.cppreference.com/w/cpp/language/tu_local)

C++ compilers do not compile header files. They compile one **translation unit** at a time, after the preprocessor has flattened every `#include` directive into a single stream of tokens. Most linker errors, duplicate-symbol bugs, and mysterious global-state bugs happen when mental models confuse a `.hpp`/`.cpp` file layout on disk with the language rules governing translation units, linkage, and the One Definition Rule (ODR).

## From source files to translation units

The C++ standard divides compilation into nine **phases of translation** (`[lex.phases]`). Phases 1–4 handle character mapping, line splicing, comment stripping, and preprocessing. In phase 4, `#include` textually pastes header contents into the `.cpp` file and macros expand. What emerges is a **translation unit** (TU): one self-contained stream of preprocessed declarations and definitions.

Phases 5–7 convert literals, concatenate adjacent string literals, and perform syntactic and semantic analysis on that single TU in isolation. Phase 8 instantiates needed templates, and phase 9 links all compiled TUs and resolves external symbols. Because phase 7 never inspects neighboring `.cpp` files, cross-file visibility rests entirely on declarations visible in the current TU.

> **Mental model.** A header file is only a convention for copying the same declarations into multiple translation units before phase 7 begins. The language proper sees only separate translation units and the linker contract between them.

## Scope, storage duration, and linkage

Three independent properties govern every named variable or function in C++: **scope**, **storage duration**, and **linkage**. Treating them as synonyms guarantees confusion, especially around the overloaded `static` keyword.

- **Scope** (`[basic.scope]`) is a compile-time lookup property: which region of source text can refer to an unqualified name.
- **Storage duration** (`[basic.stc]`) is a lifetime property: when the object's storage is allocated and released (automatic, static, thread, or dynamic).
- **Linkage** (`[basic.link]`) is a multi-declaration identity property: whether two declarations of the same name in different scopes or different translation units refer to the *same* entity.

| Linkage kind | Declared via | Shared across TUs? | Typical examples |
| --- | --- | --- | --- |
| No linkage | Block-scope locals, parameters, local classes | Never | Local `int x`, block-scope `static int hits` |
| Internal linkage | `static` at namespace scope, unnamed `namespace`, namespace-scope `const` | Private to one TU | `static void helper()`, `const int kLimit = 8;` |
| External linkage | Non-static namespace-scope entities, `extern`, `inline` globals, classes | Shared across whole program | Non-member functions, `inline constexpr`, classes |
| Module linkage | Non-exported entities in module purview | Shared within one module | Helpers inside a named C++20 module |

Notice how a block-scope `static` variable crosses axes: it has **static storage duration** (living for the entire program run) and **block scope**, yet **no linkage**—two functions each declaring `static int hits = 0;` get completely separate objects. An important subtle twist occurs when a local `static` lives inside an `inline` function with external linkage: the local variable still has no linkage itself, yet the ODR requires every TU's copy of that inline function to share the single static local object!

```cpp
// Block-scope static: static storage duration, no linkage.
int next_ticket() {
    static int counter = 0; // distinct per function, not shared by name across scopes
    return ++counter;
}

// Inline function with external linkage: all TUs share one `instance` object.
inline int& global_counter() {
    static int instance = 0;
    return instance;
}
```

## Internal linkage: static, const, and unnamed namespaces

At namespace scope, C++ grants external linkage by default. Three mechanisms switch a declaration to **internal linkage**, keeping its symbol private to the current translation unit so `.cpp` files never collide at link time.

First, applying `static` to a namespace-scope variable or function gives it internal linkage. Second, an **unnamed namespace** (`namespace { ... }`) gives internal linkage to every variable, function, class, enumeration, and template inside it (`[basic.link]`). Unlike `static`, which cannot mark a class definition, an unnamed namespace hides user-defined types and prevents ODR collisions between `struct Impl` helpers across `.cpp` files.

Third, a namespace-scope variable declared `const` (including `constexpr`, which implies `const` on objects) has internal linkage unless also marked `extern`, `inline`, or `volatile`, or previously declared external.

> **Standardese.** Under `[basic.link]`, a non-volatile, non-template, non-inline namespace-scope variable of non-exported `const`-qualified type has internal linkage unless previously declared otherwise or explicitly marked `extern`.

```cpp
namespace {
struct ScratchBuffer {   // Internal linkage: safe to define differently in another TU
    int size = 64;
};
int helper_calls = 0;    // Internal linkage; `static` here would be redundant
}

static void record_call() {
    ++helper_calls;
}

const int kDefaultPort = 8080;         // Internal linkage (const without extern/inline)
extern const int kSharedVersion = 3;   // External linkage (explicit extern overrides const rule)
```

## The One Definition Rule and inline entities

The **One Definition Rule** (`[basic.def.odr]`) separates declarations (which may appear repeatedly in a TU) from definitions (which actually allocate storage, provide a function body, or define a type). Its rules split into two tiers:

1. **Within a single translation unit**, no variable, function, class type, enumeration, or template may be defined more than once.
2. **Across the entire program**, every **odr-used** non-inline function and non-inline variable with external linkage must have **exactly one** definition. Missing definitions cause undefined-reference linker errors; duplicate definitions cause multiple-definition linker errors.

Certain entities—classes, templates, `inline` functions, and C++17 `inline` variables—*must* be defined in headers across multiple TUs. The ODR permits one definition per TU provided every TU sees identical tokens whose names resolve to the exact same entities. Changing class layout across TUs via macros is **ill-formed, no diagnostic required (IFNDR)**: the linker rarely catches it, and runtime corruption silently ensues.

```cpp
// Safe header constant since C++17: external linkage, merged to a single address.
inline constexpr int kMaxRetries = 5;

// Contrast with plain `const int kLegacyRetries = 5;` in a header:
// each TU receives its own internal-linkage copy with a distinct address.
inline const int* retry_address() {
    return &kMaxRetries; // Every TU observes the exact same pointer value
}
```

> **Pitfall.** Taking the address of a namespace-scope `const` (non-`inline`) or `static` variable inside an external `inline` function causes IFNDR: each TU resolves to a distinct object, violating ODR entity-identity rules.

Using `inline constexpr` (C++17+) avoids this trap in headers by granting external linkage and merging every TU to one object.

## Language linkage and TU-local boundaries

When calling C libraries or exposing ABI symbols, `extern "C"` specifies **language linkage** (`[dcl.link]`). It disables C++ name mangling and selects the C calling convention while leaving **C++ linkage** (internal vs. external) intact.

Two subtleties frequently catch developers off guard. First, `extern "C" { int x; }` defines `x`, whereas `extern "C" int x;` (without braces) treats `extern` as a declaration only. Second, ISO C++ treats function types with different language linkages as distinct types (`[dcl.link]`)—meaning `extern "C" void (*)(int)` differs formally from `void (*)(int)`—though GCC and Clang allow converting between them when calling conventions match.

C++20 also formalized **TU-local** entities (`[basic.link]`): entities with internal linkage or no linkage cannot be exposed from external-linkage `inline` functions or module interfaces without triggering an error.

> **Pitfall.** Inside `extern "C" { int global_flag; }`, the braces suppress the `extern` storage-class effect on `global_flag`, turning it into a tentative definition that causes duplicate-symbol errors if placed in a header. Always write `extern "C" extern int global_flag;` for header declarations inside a linkage block.

## What to remember

- A **translation unit** is the post-preprocessor token stream of a single `.cpp` file; phase 7 compiles each TU in isolation before phase 9 links them.
- **Scope** governs name lookup, **storage duration** governs object lifetime, and **linkage** governs whether declarations across scopes or TUs refer to the same entity.
- Namespace-scope `const` variables default to **internal linkage**; prefer `inline constexpr` in headers so every TU shares one object and address.
- Use **unnamed namespaces** rather than `static` when hiding types, templates, or groups of helpers inside a single `.cpp` file.
- Every odr-used external non-inline entity needs exactly one definition program-wide; inline functions, inline variables, classes, and templates require identical definitions in every TU (or else IFNDR).

## Concept Map Outline

- **Translation Units & Linkage:** Source files become isolated translation units whose symbols coordinate through linkage and the One Definition Rule.
  - **Translation Phases:** Nine ordered compilation phases turn source text and headers into linked object code.
    - **Preprocessing (Phase 4):** Textually splices included headers and expands macros to form one translation unit.
    - **Semantic Analysis (Phase 7):** Compiles one translation unit in isolation without inspecting neighboring source files.
    - **Linking (Phase 9):** Merges compiled translation units and resolves external symbol references across the program.
  - **Three Orthogonal Axes:** Every declared entity independently carries a scope, storage duration, and linkage.
    - **Scope:** Compile-time lookup rule determining where an unqualified identifier can be resolved.
    - **Storage Duration:** Lifetime rule specifying when an object's storage is allocated and destroyed.
    - **Linkage:** Identity rule deciding whether declarations in different scopes or TUs name the same entity.
  - **Linkage Kinds:** C++ partitions declarations into no linkage, internal, external, or module linkage.
    - **No Linkage:** Block-scope locals and static local variables are never shared by name across scopes.
    - **Internal Linkage:** Namespace-scope static, unnamed namespaces, and plain const globals stay private to one TU.
    - **External Linkage:** Non-static globals, classes, and inline entities resolve to the same symbol program-wide.
    - **Module Linkage:** Non-exported entities inside a module purview are shared across that module's units only.
  - **One Definition Rule:** Limits how many definitions an entity may have per translation unit and program-wide.
    - **Single Program Definition:** Each odr-used non-inline external entity must have exactly one definition in the program.
    - **Inline & Template Merging:** Classes, templates, and inline entities allow one identical definition per translation unit.
    - **IFNDR Mismatch:** Token or lookup mismatches across TUs make the program ill-formed with no diagnostic required.
  - **Language & ABI Linkage:** Controls calling conventions, name mangling, and TU-local exposure boundaries.
    - **extern "C" Blocks:** Selects C ABI linkage while braced variable declarations without extern still define storage.
    - **TU-Local Entities:** Internal-linkage entities cannot be exposed via external inline functions or module exports.

## Standardese Quiz Questions

### Question 1 [warmup] ([lex.phases])

How does the compiler handle a #include "config.hpp" directive before phase 7 semantic analysis begins?

A. It compiles config.hpp once into a cached symbol table shared across all .cpp files.
B. It defers resolving declarations in config.hpp until the linker merges object files in phase 9.
C. The preprocessor textually pastes config.hpp into the including file in phase 4 to form one translation unit.
D. It automatically assigns internal linkage to every function declared inside config.hpp.

**Answer (C):** The preprocessor textually pastes config.hpp into the including file in phase 4 to form one translation unit.

**Why:** Under [lex.phases], preprocessing in phase 4 textually inserts the contents of included headers and expands macros. Phase 7 parses the resulting single translation unit with no separate concept of a header file.

### Question 2 [warmup] ([basic.link], [namespace.unnamed])

You need a helper struct Buffer defined in two different .cpp files with different layouts and no ODR collision. Which declaration gives Buffer internal linkage?

A. namespace { struct Buffer { int len; }; }
B. static struct Buffer { int len; };
C. inline struct Buffer { int len; };
D. extern "C" struct Buffer { int len; };

**Answer (A):** namespace { struct Buffer { int len; }; }

**Why:** An unnamed namespace gives internal linkage to every declaration inside it, including class types and templates. The static specifier cannot be applied to a class definition itself.

### Question 3 [tricky] ([basic.link], [basic.def.odr])

Why does putting this header snippet into two translation units violate the One Definition Rule?

```cpp
const int kRetries = 4;
inline const int* retry_ptr() {
    return &kRetries;
}
```

A. A const variable cannot have its address taken at namespace scope.
B. Returning a pointer from an inline function makes it non-inline.
C. Taking &kRetries forces dynamic initialization across translation units.
D. kRetries has internal linkage by default, so retry_ptr() resolves to a different object in each TU (IFNDR).

**Answer (D):** kRetries has internal linkage by default, so retry_ptr() resolves to a different object in each TU (IFNDR).

**Why:** A namespace-scope const variable without extern or inline has internal linkage under [basic.link], giving each TU its own kRetries object. Because retry_ptr() has external linkage and its odr-used name kRetries resolves to different entities across TUs, the program violates [basic.def.odr] (IFNDR). Adding inline constexpr fixes this.

### Question 4 [tricky] ([dcl.link], [basic.def.odr])

What happens if a header included by two .cpp files contains `extern "C" { int shared_status; }`?

A. It compiles and links cleanly because extern suppresses allocating storage.
B. Linking fails with a duplicate definition error because braces restrict extern "C" to language linkage only.
C. shared_status automatically receives internal linkage in each translation unit.
D. It is ill-formed at compile time because variables cannot have C language linkage.

**Answer (B):** Linking fails with a duplicate definition error because braces restrict extern "C" to language linkage only.

**Why:** Inside a braced linkage-specification (`extern "C" { ... }`), extern specifies language linkage rather than external-declaration-only status ([dcl.link]). Therefore `int shared_status;` is a variable definition in every TU that includes the header.

### Question 5 [standardese] ([basic.link], [basic.stc.static], [dcl.inline])

What are the scope, storage duration, and linkage of `hits` in this inline function?

```cpp
inline int bump() {
    static int hits = 0;
    return ++hits;
}
```

A. Block scope, static storage duration, and no linkage (yet shared across TUs via bump's ODR identity).
B. Block scope, automatic storage duration, and external linkage.
C. Namespace scope, static storage duration, and internal linkage.
D. Block scope, static storage duration, and external linkage.

**Answer (A):** Block scope, static storage duration, and no linkage (yet shared across TUs via bump's ODR identity).

**Why:** A block-scope static variable has block scope, static storage duration, and no linkage ([basic.link]). However, [dcl.inline] requires that static local variables inside an inline function with external linkage refer to the same single object across all translation units.

### Question 6 [standardese] ([basic.link], [dcl.inline])

Under [basic.link], which namespace-scope declaration still has external linkage in C++17 and later?

A. const int port = 8080;
B. constexpr int port = 8080;
C. inline constexpr int port = 8080;
D. namespace { constexpr int port = 8080; }

**Answer (C):** inline constexpr int port = 8080;

**Why:** Both `const` and `constexpr` at namespace scope imply const and yield internal linkage by default unless declared `inline` or `extern` (outside an unnamed namespace). Marking a constexpr variable `inline` gives it external linkage and merges all TU definitions into one object.

# The one-definition rule

> Every entity gets one definition per translation unit, some get exactly one per program, and classes, inline functions and templates may be defined everywhere as long as every copy is the same. Most violations need no diagnostic, so they show up as wrong behaviour that changes with flags and link order.

- **Source:** C++ Atlas (https://cppatlas.com/topics/one-definition-rule)
- **Track:** Program structure
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [basic.def.odr] (https://eel.is/c++draft/basic.def.odr), [basic.def] (https://eel.is/c++draft/basic.def), [dcl.inline] (https://eel.is/c++draft/dcl.inline), [basic.link] (https://eel.is/c++draft/basic.link), [expr.prim.lambda.capture] (https://eel.is/c++draft/expr.prim.lambda.capture), [temp.expl.spec] (https://eel.is/c++draft/temp.expl.spec)
- **cppreference links:** [Definitions and ODR](https://en.cppreference.com/w/cpp/language/definition), [inline specifier](https://en.cppreference.com/w/cpp/language/inline), [Translation-unit-local entities](https://en.cppreference.com/w/cpp/language/tu_local)
- **Prerequisites:** translation-units-and-linkage

## The one idea

The one-definition rule, the ODR, is the contract that lets separate compilation work. The compiler sees one translation unit at a time and trusts that what it sees there agrees with what every other translation unit sees. The rule has three layers:

1. Within one translation unit, nothing may be defined twice.
2. In the whole program, every non-inline function or variable that is odr-used must be defined exactly once.
3. Classes, enumerations, inline functions, inline variables, templates and a few others may be defined in several translation units, but every definition must be the same, in a strong, token-level sense.

The first layer is checked by the compiler. The second is usually caught by the linker. The third is, for the most part, **ill-formed, no diagnostic required**: the program is broken, nobody is obliged to tell you, and the resulting behaviour is not constrained by the standard.

> **Mental model.** The ODR lets the program behave as if each entity has one definition. Repeating a definition is allowed only where the copies are interchangeable, and the toolchain is free to keep any one of them and throw the rest away.

## One per translation unit, one per program

The per-translation-unit rule is simple and diagnosed. Two definitions of the same class, function or variable in one translation unit are an error, which is what include guards exist to prevent.

The program-wide rule applies to non-inline functions and variables. If such an entity is odr-used, at least one definition must exist somewhere, and if more than one exists in different translation units the program is ill-formed. Neither failure needs a diagnostic, because no single compilation can see it. In practice the linker reports an undefined symbol or a duplicate symbol, but the standard does not promise even that.

```cpp
// helpers.h, included by two .cpp files
int clamp_to_byte(int v) { return v < 0 ? 0 : v > 255 ? 255 : v; }
// two external definitions: ill-formed; usually a duplicate-symbol link error
// fix: mark it inline, or declare it here and define it in one .cpp file
```

A full explicit specialization of a function template is an ordinary function for this purpose. It is not a template, so it is not implicitly inline. Defining `template<> void log<int>(int) { ... }` in a header without `inline` gives one definition per translation unit and the same duplicate-symbol problem.

## Odr-use: when a definition is actually needed

Only odr-used entities need a definition. A function is odr-used when a potentially evaluated expression names it, which covers calls and taking its address. A variable is odr-used when a potentially evaluated expression names it, unless the variable is usable in constant expressions and the expression immediately reads its value, or the expression is a discarded-value expression that does not read it. Binding a reference to the variable, or taking its address, is an odr-use.

The classic casualty is a `static const` data member with an in-class initializer. Reading its value is not an odr-use, but passing it to `std::min`, which takes `const T&`, is.

```cpp
#include <algorithm>

struct Limits { static const int max_items = 64; };  // declaration, not a definition

int clamp_count(int n) {
  int a = Limits::max_items;             // fine: only the value is read
  return std::min(n, Limits::max_items) + a;  // odr-use: binds const int&
}
// without "const int Limits::max_items;" in some .cpp file, GCC and Clang fail to link at -O0;
// at -O2 the call is inlined and it may link anyway
```

Since C++17 the fix is `static constexpr int max_items = 64;`, because a `constexpr` static data member is implicitly an inline variable and its in-class declaration is a definition. The fact that the broken version links at `-O2` is exactly what "no diagnostic required" looks like.

Odr-use also decides what a lambda must capture. A local `const int` initialized with a constant can be read inside a lambda without any capture, because reading it is not an odr-use; taking its address is, and requires a capture.

```cpp
void demo() {
  const int n = 3;
  auto twice = [] { return n * 2; };   // OK: n is not odr-used
  // auto where = [] { return &n; };   // ill-formed: odr-use of n requires a capture
  (void)twice;
}
```

## Many definitions that must be one

For a class, enumeration, inline function, inline variable, templated entity, concept, and a few more, a program may contain one definition per translation unit. [basic.def.odr] then demands that the definitions agree. The main requirements are:

- each definition consists of the **same sequence of tokens**;
- each name in the definitions refers to the **same entity**, after overload resolution, with a narrow exception for constants whose values are read but which are not odr-used;
- overloaded operators, conversions and allocation functions used in the definitions are the same;
- corresponding entities have the same language linkage;
- default arguments used in the definitions satisfy the same requirements;
- for templates, the rules also apply to names looked up at the point of instantiation.

When these hold, the program behaves as if there were one definition. When they do not, and the definitions are not attached to a named module, the program is ill-formed with no diagnostic required.

The same tokens are not enough. Each name must also find the same entity. A `constexpr` variable at namespace scope has internal linkage, so each translation unit has its own copy, and an inline function that odr-uses it refers to a different object in each translation unit.

```cpp
// limits.h, included by several .cpp files
constexpr int max_depth = 32;              // internal linkage: one object per TU

inline int depth_value() { return max_depth; }        // OK: value read, not odr-used
inline const int& depth_ref() { return max_depth; }   // ODR violation: binds a reference
// fix: inline constexpr int max_depth = 32;  (one program-wide object)
```

> **Standardese.** [basic.def.odr] allows a name in the definition to refer to a different object in each translation unit only if the object is a non-volatile `const` object with internal or no linkage, has the same literal type and value in every definition, is initialized with a constant expression, and is not odr-used. `depth_value` satisfies that, and `depth_ref` does not.

Lambda expressions follow the same pattern. A lambda inside an inline function or a template has the same closure type in every translation unit, because the definition containing it is "the same". A lambda that initializes a namespace-scope `constexpr` variable does not: the variable has internal linkage, so each translation unit gets its own variable of its own closure type, and any inline function that calls it refers to different entities in different translation units. Declare such variables `inline constexpr`.

## How violations bite

Because no diagnostic is required, ODR violations rarely fail loudly. These are the common shapes:

- A header defines a struct differently depending on a macro, such as a debug-only member guarded by `#ifndef NDEBUG`, and two libraries are built with different settings. Each side computes different offsets and sizes for the "same" class.
- Two libraries each define a helper with the same name, such as `inline int version()`, or a class called `Node`, with different bodies, in the global namespace.
- A file is compiled with flags that change the meaning of the tokens, such as a different `#pragma pack`, a different `-D` value, or a different language standard that changes a library type's layout.
- A function is declared `inline` in one translation unit and not in another.

The second shape is easy to reproduce. Two translation units define `inline int version()` returning 1 and 2, and each calls it. With GCC 16 at `-O0` both calls return the same value, which one depends on the link order. At `-O2` each call is inlined and returns its own translation unit's value. None of these outcomes is a bug in the compiler.

> **Pitfall.** `static` inline functions and functions in unnamed namespaces are immune, because each translation unit has its own entity. That is also a cost: a `static inline` function in a header gives each translation unit its own copy of any `static` local variable, so a counter or cache in it is silently per-translation-unit.

The rule for inline declarations has its own quiet trap. [dcl.inline] requires that if a function with external linkage is declared `inline` in one translation unit, an inline declaration is reachable in every translation unit that declares it, with no diagnostic required. In practice, an inline function is only emitted where it is odr-used. If the translation unit that sees `inline` never calls it, another translation unit that declared it non-inline gets an undefined-symbol error. If it does call it, the program may link at `-O0` and stop linking at `-O2`, once that call is inlined.

## Vague linkage: how implementations cope

The standard only says "behave as if there is one definition". Implementations deliver that with **vague linkage**. On ELF and Mach-O platforms that use the Itanium C++ ABI, a compiler emits every inline function, inline variable, template instantiation, static local guard variable and `typeinfo` object it needs as a weak or COMDAT symbol. The linker keeps one copy of each and discards the others without comparing them. On macOS, `nm -m` shows such a symbol as `weak external`.

```text
a.o:  weak external  version()   -> returns 1
b.o:  weak external  version()   -> returns 2
          \                         /
           linker keeps the first one it sees;
           calls that were inlined keep their own copy
```

Virtual tables follow a related convention. The Itanium ABI emits a class's vtable in the translation unit that defines its **key function**, the first non-inline, non-pure virtual member function. Without one, the vtable is emitted with vague linkage wherever it is needed.

Some tools can find ODR violations that compilers are not required to diagnose. GCC's link-time optimizer warns about mismatched type definitions with `-flto -Wodr`, enabled by default under LTO, and on Linux AddressSanitizer can report some global variables that are defined twice. Neither compares inline function bodies; in the `version()` example above, GCC 16 with `-flto -Wodr` says nothing.

Since C++20, definitions attached to a named module change the picture: an importer reaches the module's one definition instead of compiling its own copy, and a second definition is diagnosable when an earlier one is reachable. The modules topic covers that in detail.

## What to remember

- One definition per translation unit is diagnosed; one per program for non-inline functions and variables is not, and usually surfaces at link time.
- Only odr-used entities need definitions; binding a reference or taking an address is an odr-use, reading a constant's value is not.
- `static constexpr` data members are inline since C++17 and need no out-of-line definition.
- Repeated definitions of classes, inline entities and templates must have the same tokens and must find the same entities.
- An inline function that odr-uses a namespace-scope `constexpr` variable violates the ODR; use `inline constexpr`.
- Explicit specializations of function templates are not implicitly inline.
- ODR violations are ill-formed, no diagnostic required; results change with optimization level and link order.
- Vague linkage keeps one arbitrary copy of each inline entity; `-flto -Wodr` catches type mismatches, not differing function bodies.

## Concept Map Outline

- **One-definition rule:** The program must behave as if each entity had exactly one definition.
  - **Three layers:** Per translation unit, per program, and repeated definitions that must match.
    - **One per TU:** Two definitions of anything in one translation unit are diagnosed.
    - **One per program:** Non-inline odr-used functions and variables need exactly one definition overall.
    - **Repeatable items:** Classes, enums, inline entities, templates and concepts may be defined once per TU.
  - **Odr-use:** Only odr-used entities need a definition to exist.
    - **Reading a constant:** An immediate read of a variable usable in constant expressions is not an odr-use.
    - **References and addresses:** Binding a reference or taking the address is an odr-use, as with std::min(x, S::n).
    - **Lambda captures:** A lambda may read a local constant uncaptured but must capture it to take its address.
    - **static constexpr:** Since C++17 constexpr static members are inline and need no out-of-class definition.
  - **Same definitions:** Repeated definitions must match token for token and in meaning.
    - **Same tokens:** Each definition must consist of the same sequence of tokens.
    - **Same entities:** Names must find the same entities after overload resolution in every TU.
    - **Constant exception:** Internal-linkage constants may differ per TU only if they are not odr-used.
    - **Lambdas:** Lambdas in inline functions share one closure type; namespace-scope constexpr ones do not.
  - **How it bites:** Violations are ill-formed, no diagnostic required, so nothing has to warn you.
    - **Macros and flags:** NDEBUG, -D values or #pragma pack can make one class two layouts.
    - **Name clashes:** Two libraries' inline version() or Node with different bodies in one namespace.
    - **Varies with -O:** At -O0 the linker's copy wins; at -O2 each TU may inline its own body.
    - **Missing inline:** inline in one TU but not another is ill-formed and may fail to link at -O2.
  - **Vague linkage:** Implementation practice: emit weak or COMDAT copies and keep one.
    - **Weak symbols:** Inline functions, template instantiations and guard variables; nm -m shows weak external.
    - **Key function:** Itanium ABI emits a vtable with the first non-inline, non-pure virtual function.
    - **Detection tools:** GCC -flto -Wodr catches mismatched types but not differing inline function bodies.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.def.odr])

This header is included by `a.cpp` and `b.cpp`, which are linked into one program. What does the standard say?

```cpp
// util.h
int twice(int x) { return 2 * x; }
```

A. Well-formed: the two definitions are token-for-token identical
B. Ill-formed, and the compiler must issue a diagnostic
C. Well-formed: the linker is required to keep one copy
D. Ill-formed, no diagnostic required; linkers usually report a duplicate symbol

**Answer (D):** Ill-formed, no diagnostic required; linkers usually report a duplicate symbol

**Why:** `twice` is a non-inline function with external linkage, so the program may contain only one definition of it. Two translation units each contain one, which [basic.def.odr] makes ill-formed, and because the definitions are not attached to a named module no diagnostic is required; no single compilation can see both. The identical-tokens answer is tempting, but that permission only applies to inline functions, classes, templates and the other entities [basic.def.odr] lists.

### Question 2 [warmup] ([basic.def.odr], [class.static.data])

There is no definition of `S::n` outside the class. Which function odr-uses `S::n`, so that the program needs such a definition?

```cpp
#include <algorithm>

struct S { static const int n = 5; };

int a()    { return S::n; }
int b()    { return S::n + 1; }
int c(int k) { return std::max(k, S::n); }
int d()    { int arr[S::n]{}; return arr[0]; }
```

A. `a`
B. `b`
C. `c`
D. `d`

**Answer (C):** `c`

**Why:** `S::n` is usable in constant expressions, so an expression that immediately reads its value does not odr-use it; that covers `a`, `b` and the array bound in `d`. `std::max` takes its arguments by `const int&`, and binding a reference to `S::n` is an odr-use, so `c` requires a definition, and GCC and Clang fail to link it at `-O0`. Since C++17, `static constexpr int n = 5;` would be an inline variable and need no extra definition.

### Question 3 [warmup] ([basic.def.odr], [temp.expl.spec])

Which of these may be defined, identically, in several translation units of one program?

A. A non-inline function `int f() { return 1; }`
B. A class `struct Point { int x, y; };`
C. A namespace-scope variable `int counter = 0;`
D. A full explicit specialization `template<> int g<int>() { return 1; }` without `inline`

**Answer (B):** A class `struct Point { int x, y; };`

**Why:** Classes are among the definable items that [basic.def.odr] allows once per translation unit, provided every definition is the same. The explicit specialization is the tempting wrong answer: it lives next to a template, but a full specialization of a function template is an ordinary function and is not implicitly inline, so repeating it is an ODR violation. The non-inline function and the non-inline variable may have only one definition in the program.

### Question 4 [tricky] ([basic.def.odr], [dcl.inline])

`a.cpp` contains `inline int version() { return 1; }` and `b.cpp` contains `inline int version() { return 2; }`. Both call `version()`, and both are linked into one program. What does the standard say?

A. It is unspecified which of the two definitions is used
B. Well-formed: each translation unit uses its own definition
C. The program is ill-formed, no diagnostic required
D. Ill-formed, and the linker must diagnose the mismatch

**Answer (C):** The program is ill-formed, no diagnostic required

**Why:** Inline functions may be defined in several translation units only if every definition consists of the same tokens with the same meaning. These do not, so [basic.def.odr] makes the program ill-formed with no diagnostic required, which places no requirement on its behaviour. "Unspecified" is tempting because it describes what you observe: GCC 16 at `-O0` uses one body for both calls, chosen by link order, and at `-O2` inlines each translation unit's own body. That observation is not a guarantee of anything.

### Question 5 [tricky] ([basic.def.odr], [basic.link])

This header is included by several translation units of one program. What is its status?

```cpp
// limits.h
constexpr int max_depth = 32;

inline const int& depth_ref() { return max_depth; }
```

A. Ill-formed, no diagnostic required: `depth_ref` refers to a different object in each translation unit
B. Well-formed: `max_depth` is constexpr, so every translation unit sees the same value
C. Well-formed, but `depth_ref()` returns a dangling reference
D. Ill-formed: a constexpr variable cannot be returned by reference

**Answer (A):** Ill-formed, no diagnostic required: `depth_ref` refers to a different object in each translation unit

**Why:** A namespace-scope `constexpr` variable is `const` and therefore has internal linkage, so each translation unit has its own `max_depth`. The inline function's definitions are token-identical but name different entities, and the exception for constants only applies when the constant is not odr-used; binding the returned reference odr-uses it. The "same value" answer is right for `return max_depth;` by value, which is why it tempts. Declaring the variable `inline constexpr` fixes it.

### Question 6 [tricky] ([dcl.inline], [basic.def.odr])

The header defines `inline int next() { static int n = 0; return ++n; }`. `a.cpp` includes it and defines `int fa() { return next(); }`. `main.cpp` also includes it. What does this `main.cpp` print?

```cpp
#include <cstdio>

inline int next() { static int n = 0; return ++n; }
int fa();

int main() {
  int x = fa();
  int y = next();
  std::printf("%d %d\n", x, y);
}
```

A. `1 1`, because each translation unit has its own `n`
B. `1 2`
C. Either `1 1` or `1 2`, depending on inlining
D. Undefined behavior, because `n` is defined in two translation units

**Answer (B):** `1 2`

**Why:** An inline function with external linkage is one entity across the program, and a static local variable in it is one object, whichever translation unit's copy runs. So `fa()` returns 1 and the later `next()` returns 2, regardless of optimization. `1 1` is what you would get from `static inline int next()`, which gives each translation unit a separate function and therefore a separate `n`.

### Question 7 [standardese] ([basic.def.odr], [expr.prim.lambda.capture])

Which lambda makes `demo` ill-formed?

```cpp
void demo() {
  const int n = 3;
  auto a = [] { return n; };
  auto b = [] { return n * 2; };
  auto c = [] { return sizeof(n); };
  auto d = [] { return &n; };
}
```

A. `a`, because `n` is not captured
B. `d`
C. `c`, because `sizeof` names `n`
D. None of them; `n` has automatic storage but is a constant

**Answer (B):** `d`

**Why:** A lambda without a capture default may only name a local entity if doing so is not an odr-use. `n` is a `const int` initialized with a constant, so it is usable in constant expressions, and reading its value in `a` and `b` is not an odr-use; `sizeof(n)` is an unevaluated operand. Taking its address in `d` is an odr-use, which requires a capture, so `demo` is ill-formed and GCC and Clang reject it. Option `a` is the tempting answer for anyone who expects every outside variable to need a capture.

### Question 8 [standardese] ([dcl.inline], [basic.def.odr])

`a.cpp` defines `inline int helper() { return 42; }`. `b.cpp` declares `int helper();` without `inline` and calls it. What does the C++23 standard say?

A. Well-formed: `a.cpp` provides the definition the linker needs
B. Well-formed only if `a.cpp` also calls `helper`
C. Ill-formed, and a diagnostic is required at link time
D. Ill-formed, no diagnostic required: an inline declaration must be reachable in every translation unit that declares the function

**Answer (D):** Ill-formed, no diagnostic required: an inline declaration must be reachable in every translation unit that declares the function

**Why:** [dcl.inline] requires that if a function with external linkage is declared inline in one definition domain, an inline declaration of it is reachable from the end of every definition domain that declares it, with no diagnostic required, and `b.cpp` breaks that rule. [basic.def.odr] separately requires an inline function to be defined wherever it is odr-used, which `b.cpp` also fails. The second option describes what happens in practice with GCC at `-O0`, where `a.cpp` emits an out-of-line copy only if it uses the function, but that copy may vanish at `-O2` and the program then fails to link.

# Name Lookup, Qualified Lookup, and ADL

> Trace how the compiler maps an identifier to candidate declarations across unqualified lookup, qualified lookup, Argument-Dependent Lookup, and two-phase template lookup.

- **Source:** C++ Atlas (https://cppatlas.com/topics/name-lookup-and-adl)
- **Track:** Program structure
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [basic.lookup.unqual] (https://eel.is/c++draft/basic.lookup.unqual), [basic.lookup.qual] (https://eel.is/c++draft/basic.lookup.qual), [basic.lookup.argdep] (https://eel.is/c++draft/basic.lookup.argdep), [namespace.udir] (https://eel.is/c++draft/namespace.udir), [temp.res] (https://eel.is/c++draft/temp.res)
- **cppreference links:** [Name lookup](https://en.cppreference.com/w/cpp/language/lookup), [Unqualified name lookup](https://en.cppreference.com/w/cpp/language/unqualified_lookup), [Qualified name lookup](https://en.cppreference.com/w/cpp/language/qualified_lookup), [Argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl), [Using-declaration](https://en.cppreference.com/w/cpp/language/using_declaration), [Dependent names](https://en.cppreference.com/w/cpp/language/dependent_name), [Friend declaration](https://en.cppreference.com/w/cpp/language/friend)
- **Prerequisites:** translation-units-and-linkage

When the compiler sees an expression like `process(x)` or `ns::find(y)`, it does not jump straight to matching parameter types or checking `private` access. It runs a strict multi-stage pipeline where **name lookup** executes first, completely blind to argument types (except during Argument-Dependent Lookup) and access specifiers.

## Lookup precedes overload resolution and access checking

Every function call passes through four sequential stages:

1. **Name lookup** collects candidate declarations from scopes determined by syntax.
2. **Template argument deduction** synthesizes specializations for any function templates found.
3. **Overload resolution** ranks the viable candidates by argument conversion sequences.
4. **Access control** verifies that the chosen declaration is `public` or accessible via friendship.

Because lookup finishes before overload resolution begins, an inner scope declaration **hides** outer declarations of the same name regardless of signature. Likewise, because access checking happens *last*, a `private` overload with a better parameter match wins overload resolution and then triggers an access error rather than falling back to a worse `public` overload.

> **Mental model.** Name lookup builds the candidate menu by name alone; overload resolution picks the best dish from that menu; access control checks whether you are allowed to order it.

## Unqualified lookup and name hiding

**Unqualified name lookup** (`[basic.lookup.unqual]`) searches outward from the point of use through enclosing block, class (including base classes), and namespace scopes—stopping at the **first** scope that contains at least one declaration of that name. Once a declaration is found, outer scopes are never examined, even if parameter types do not match.

This hiding rule catches programmers off guard in derived classes. Declaring `void log(int)` in `Derived` hides every `log` overload in `Base`—including `void log(const std::string&)`—unless `using Base::log;` pulls the base overload set into `Derived` scope.

```cpp
#include <string>

struct Base {
    void log(double) {}
};

struct Derived : Base {
    using Base::log; // Without this, Base::log(double) is hidden by Derived::log(int)
    void log(int) {}
};

void run_lookup() {
    Derived d;
    d.log(3.5); // Resolves to Base::log(double) thanks to using-declaration
    d.log(42);  // Resolves to Derived::log(int)
}
```

Unqualified lookup interacts subtly with `using` declarations versus `using namespace` directives. A `using ns::foo;` declaration introduces `foo` as a synonym in the *current* declarative region—so it participates in overloading, hides outer declarations, and is visible to qualified lookup. By contrast, a `using namespace ns;` directive (`[namespace.udir]`) instructs unqualified lookup to search `ns` as if its members were declared in the nearest common enclosing namespace of the directive and `ns`. It does not inject names into the current scope itself.

| Mechanism | Scope where name appears | Participates in qualified lookup? | Can cause ambiguity with local name? |
| --- | --- | --- | --- |
| Unqualified declaration | Current block, class, or namespace | Yes, via enclosing qualifier | Redefinition or overload |
| `using ns::name;` | Current declarative region | Yes (`Current::name`) | Yes, conflicts with identical signature |
| `using namespace ns;` | Nearest common enclosing namespace | Never (`Current::name` ignores it) | Only if unqualified lookup reaches both |

## Qualified name lookup and using-declarations

When a name follows `::`, `.`, or `->`, the compiler performs **qualified name lookup** (`[basic.lookup.qual]`). Qualified lookup searches strictly inside the named class (and its base classes) or namespace (and any `inline namespace` members plus transitive `using namespace` directives inside that namespace—ignoring directives in the caller's scope).

Crucially, **qualified lookup disables Argument-Dependent Lookup**. Writing `std::swap(a, b)` forces lookup inside `namespace std` alone and refuses to consider a custom `swap` defined alongside user types. Also worth noting is the **injected-class-name**: inside any class `Widget` (or template `Box<T>`), the bare name `Widget` (or `Box`) is injected into the class scope itself, which is why `Widget::Widget` names the constructor and `Box` inside `Box<T>` denotes `Box<T>`.

## Argument-Dependent Lookup and hidden friends

Why does `std::cout << "hello"` compile without writing `std::operator<<(std::cout, "hello")`? Because of **Argument-Dependent Lookup (ADL)** (`[basic.lookup.argdep]`), also called Koenig lookup. When an unqualified function call uses a bare function name (not parenthesized and not qualified with `::`), the compiler augments ordinary unqualified lookup by searching the **associated namespaces and classes** of every argument's type.

> **Standardese.** Under `[basic.lookup.argdep]`, ADL is bypassed completely if ordinary unqualified lookup finds a class member declaration, a block-scope function declaration (that is not a using-declaration), or any declaration that is neither a function nor a function template.

Each argument type contributes associated namespaces and classes according to its structure:

- **Class types** contribute the class itself, its enclosing namespace (plus inline namespace parents), and all direct and indirect base classes along with their enclosing namespaces.
- **Class template specializations** contribute the same namespaces as a non-template class, plus the associated namespaces of template type arguments (so `std::vector<geom::Vec>` brings in both `std` and `geom`).
- **Fundamental types** (`int`, `double`, pointers to them) contribute **zero** associated namespaces.

One of the cleanest idioms in modern C++—**hidden friends**—relies entirely on ADL. A `friend` function defined *inline inside a class body* is a member of the enclosing namespace, yet is **invisible** to ordinary qualified or unqualified lookup (`geom::operator+` fails). It can *only* be found by ADL when an argument of that class type appears in the call. Hidden friends keep namespace overload sets tiny, improve compile times, and prevent unintended implicit conversions when unrelated types are passed.

```cpp
#include <utility>

namespace geom {
struct Vec {
    int x, y;

    // Hidden friend: visible only via ADL when Vec is an argument.
    friend Vec operator+(Vec a, Vec b) {
        return {a.x + b.x, a.y + b.y};
    }
};

int norm_sq(Vec v) {
    return v.x * v.x + v.y * v.y;
}
} // namespace geom

template<class T>
void generic_swap(T& a, T& b) {
    using std::swap; // Fallback for types without custom swap
    swap(a, b);      // Unqualified call triggers ADL for T's namespace
}

int test_adl() {
    geom::Vec u{1, 2}, v{3, 4};
    geom::Vec sum = u + v; // Finds hidden friend operator+ via ADL
    // (norm_sq)(sum);     // Parentheses suppress ADL: ill-formed here
    generic_swap(u, v);
    return norm_sq(sum);   // Unqualified id triggers ADL into geom
}
```

> **Pitfall.** Parenthesizing a function name—`(func)(arg)`—turns the callee from an unqualified-id into a parenthesized expression, which **disables ADL** just like `ns::func(arg)`. Standard C++20 customization point objects (like `std::ranges::sort`, nicknamed *niebloids*) are function objects rather than function declarations, intentionally blocking ADL at call sites while internally performing controlled customization dispatch.

## Two-phase lookup in templates

Templates resolve names in two distinct phases (`[temp.res]`):

- **Phase 1 (template definition time):** All **non-dependent names** (names that do not depend on a template parameter) are resolved immediately using ordinary unqualified or qualified lookup in the template's definition context—**without** ADL.
- **Phase 2 (template instantiation time):** **Dependent names** (such as `f(t)` where `t` has dependent type `T`) are looked up in the template's definition context *and*, via ADL only, in the instantiation context.

This split explains why `Derived<T>` inheriting from dependent `Base<T>` cannot write bare `count` inside member functions: `count` is syntactically non-dependent, and in phase 1 the compiler refuses to look inside `Base<T>` because a future explicit specialization of `Base<int>` could omit or alter `count`. Writing `this->count` or `Base<T>::count` makes the lookup dependent, deferring resolution to phase 2.

> **Pitfall.** Defining an unqualified helper `void trace(int)` *after* a template definition does not make `trace(t)` find it during phase 2 when `T = int`. Phase 2 looks in the instantiation context **only via ADL**, and fundamental types like `int` have no associated namespaces.

```cpp
template<class T>
struct Store {
    int count = 1;
};

template<class T>
struct CachedStore : Store<T> {
    int read() const {
        // `return count;` would fail Phase 1 lookup (non-dependent name ignores Store<T>).
        return this->count; // Dependent member access defers lookup to Phase 2
    }
};
```

## What to remember

- The compiler always resolves **name lookup** before template deduction, overload resolution, and access control; inner names hide outer names regardless of signature, and `private` best matches still win overload resolution and fail access checks.
- **Qualified lookup** (`ns::f`, `obj.f`) and parenthesized callees (`(f)(x)`) disable ADL.
- **ADL** searches associated namespaces and classes of argument types unless ordinary lookup finds a class member, a block-scope function declaration, or a non-function.
- **Hidden friends** defined inline inside a class are reachable exclusively through ADL, preventing accidental overload pollution.
- **Two-phase lookup** resolves non-dependent names at template definition time and dependent names at instantiation time (via ADL for unqualified calls).

## Concept Map Outline

- **Name Lookup & ADL:** Maps identifiers to candidate declarations before template deduction, overload resolution, and access control run.
  - **Lookup Pipeline:** Runs strictly before deduction, overload ranking, and private/protected access checks.
    - **Name Hiding First:** Inner scopes stop lookup before parameter types are ever compared.
    - **Access Checking Last:** Overload resolution can select a private best match and then fail access control.
  - **Unqualified Lookup:** Searches outward through enclosing blocks, classes, and namespaces until the first match.
    - **using-declarations:** Brings base or namespace names into the current scope so overloads stay visible.
    - **using-directives:** Exposes namespace members from the nearest common enclosing namespace for unqualified calls.
  - **Qualified Lookup:** Inspects only the named class or namespace scope and disables ADL.
    - **Scope Qualifier :::** Confines search to the target namespace or class hierarchy while ignoring caller directives.
    - **Injected Class Name:** Places the class's own name inside its scope so templates and constructors resolve.
  - **Argument-Dependent Lookup:** Extends unqualified function calls into the associated namespaces and classes of arguments.
    - **Associated Namespaces:** Contributed by class types, bases, enclosing namespaces, and template arguments.
    - **Hidden Friends:** Inline friend definitions inside a class are callable solely via ADL.
    - **ADL Suppression:** Blocked by scope qualification, parentheses around callee, class members, or block declarations.
  - **Two-Phase Template Lookup:** Separates non-dependent lookup at template definition from dependent lookup at instantiation.
    - **Phase 1 (Definition):** Resolves non-dependent names early and ignores dependent base classes like Base<T>.
    - **Phase 2 (Instantiation):** Looks up dependent calls via ADL in instantiation context, missing fundamental types.

## Standardese Quiz Questions

### Question 1 [warmup] ([namespace.udecl], [basic.lookup.unqual])

What is the role of `using Base::log;` inside a derived class that defines `void log(int)` when `Base` defines `void log(double)`?

A. It marks Base::log as virtual so Derived can override it.
B. It prevents Derived::log(int) from hiding Base::log(double) during name lookup.
C. It enables Argument-Dependent Lookup across Base's namespace.
D. It suppresses access checking on private members of Base.

**Answer (B):** It prevents Derived::log(int) from hiding Base::log(double) during name lookup.

**Why:** Without `using Base::log;`, unqualified lookup finds `log` in `Derived` and stops before inspecting `Base`, hiding `Base::log(double)`. A using-declaration introduces the base overloads into `Derived` scope so overload resolution can choose among all of them.

### Question 2 [warmup] ([basic.lookup.argdep])

Which call disables Argument-Dependent Lookup when invoking a free function `process` on an object `v` of type `geom::Vec`?

A. process(v);
B. using geom::process; process(v);
C. (process)(v);
D. a + b; // where operator+ is a hidden friend

**Answer (C):** (process)(v);

**Why:** ADL only applies when the postfix expression of a function call is an unqualified-id. Wrapping `process` in parentheses `(process)(v)` or qualifying it (`geom::process(v)`) suppresses ADL.

### Question 3 [tricky] ([class.access], [over.match])

What happens when calling `w.emit(42)` on this class?

```cpp
struct Writer {
    void emit(double) {}
private:
    void emit(int) {}
};
void test(Writer& w) { w.emit(42); }
```

A. It calls public emit(double) because private overloads are hidden from callers.
B. It is ambiguous because both overloads accept 42.
C. It compiles with a warning and converts 42 to double.
D. It fails to compile with an access error because overload resolution selects private emit(int) before checking access.

**Answer (D):** It fails to compile with an access error because overload resolution selects private emit(int) before checking access.

**Why:** Name lookup collects all `emit` members regardless of access specifier, overload resolution selects `emit(int)` as an exact match over `emit(double)`, and access control runs last and rejects the call to private `emit(int)`.

### Question 4 [tricky] ([temp.dep], [temp.res])

Why does `return value;` inside `Derived<T>::get()` fail to compile when `Base<T>` defines `int value = 1;`?

```cpp
template<class T> struct Base { int value = 1; };
template<class T> struct Derived : Base<T> {
    int get() const { return value; }
};
```

A. Because `value` is a non-dependent name, Phase 1 lookup runs at template definition time and does not inspect dependent base class Base<T>.
B. Because data members of template bases are always private unless marked protected.
C. Because `const` member functions cannot access inherited non-const fields.
D. Because ADL only finds functions, not data members.

**Answer (A):** Because `value` is a non-dependent name, Phase 1 lookup runs at template definition time and does not inspect dependent base class Base<T>.

**Why:** Under two-phase name lookup ([temp.res]), non-dependent unqualified names inside a template are looked up during Phase 1 without inspecting dependent base classes like `Base<T>`, since an explicit specialization could redefine `Base<T>`. Writing `this->value` or `Base<T>::value` makes it dependent.

### Question 5 [standardese] ([basic.lookup.argdep])

Under [basic.lookup.argdep], which declaration found by ordinary unqualified lookup prevents ADL from running for `swap(a, b)`?

```cpp
namespace ns { struct Item {}; void swap(Item&, Item&); }
void run(ns::Item& a, ns::Item& b) {
    void swap(int&, int&);
    swap(a, b);
}
```

A. Only if `swap(int&, int&)` is a better match than `ns::swap`.
B. A block-scope function declaration that is not a using-declaration suppresses ADL completely, making `swap(a, b)` ill-formed.
C. A `using std::swap;` declaration inside `run` suppresses ADL just like a function declaration.
D. ADL still runs and finds `ns::swap` because `int&` cannot bind to `ns::Item`.

**Answer (B):** A block-scope function declaration that is not a using-declaration suppresses ADL completely, making `swap(a, b)` ill-formed.

**Why:** [basic.lookup.argdep] specifies that if ordinary unqualified lookup finds a block-scope function declaration (that is NOT a using-declaration), a class member, or a non-function, ADL is not performed. By contrast, `using std::swap;` is a using-declaration and intentionally allows ADL.

### Question 6 [standardese] ([basic.lookup.argdep])

Why does `std::vector<geom::Vec>` allow ADL on `f(vec)` to search `namespace geom` in addition to `namespace std`?

A. Because `std::vector` places a `using namespace geom;` directive inside `std`.
B. Because ADL always searches every namespace declared before the call site.
C. Because associated namespaces of a class template specialization include the associated namespaces of its template type arguments.
D. Because `geom::Vec` inherits from `std::vector` implicitly.

**Answer (C):** Because associated namespaces of a class template specialization include the associated namespaces of its template type arguments.

**Why:** Under [basic.lookup.argdep], the set of associated namespaces and classes of a class template specialization includes not only its own enclosing namespace and bases, but also the associated namespaces and classes of its template type arguments (and template template arguments).

# Namespaces and scope

> A scope is the stretch of program text where a declaration can be found by unqualified lookup, and a namespace is a scope you can name, reopen and nest. Points of declaration, shadowing, using-directives and inline namespaces all follow from a few precise rules.

- **Source:** C++ Atlas (https://cppatlas.com/topics/namespaces-and-scope)
- **Track:** Program structure
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [basic.scope.scope] (https://eel.is/c++draft/basic.scope.scope), [basic.scope.pdecl] (https://eel.is/c++draft/basic.scope.pdecl), [basic.scope.block] (https://eel.is/c++draft/basic.scope.block), [basic.namespace] (https://eel.is/c++draft/basic.namespace), [namespace.def] (https://eel.is/c++draft/namespace.def), [namespace.unnamed] (https://eel.is/c++draft/namespace.unnamed), [namespace.alias] (https://eel.is/c++draft/namespace.alias), [namespace.udir] (https://eel.is/c++draft/namespace.udir)
- **cppreference links:** [Scope](https://en.cppreference.com/w/cpp/language/scope), [Namespaces](https://en.cppreference.com/w/cpp/language/namespace), [Namespace aliases](https://en.cppreference.com/w/cpp/language/namespace_alias), [Unqualified name lookup](https://en.cppreference.com/w/cpp/language/unqualified_lookup), [Conflicting declarations](https://en.cppreference.com/w/cpp/language/conflicting_declarations)
- **Prerequisites:** translation-units-and-linkage

## The one idea

Every declaration lives in a **scope**, and from its point of declaration onward, unqualified lookup inside that scope, and inside the scopes nested in it, can find it. Scopes nest: a block inside a function, a function inside a namespace, namespaces inside the global namespace. Lookup walks that nesting from the inside out.

A **namespace** is the one kind of scope you can name, close, and open again later, possibly in another file. Everything else in this topic, from shadowing to inline namespaces, is a consequence of where a scope begins, what it contains, and how using-directives splice one namespace's names into another's lookup.

> **Mental model.** Think of scopes as nested boxes of program text. A name is visible from the point just after its declarator to the end of its box, and an inner box can hide an outer name by declaring the same one.

## The kinds of scope

C++23 lists these kinds of scope in [basic.scope]: the global scope, which is the namespace scope of the global namespace; namespace scopes; class scopes; enumeration scopes; block scopes; function parameter scopes; lambda scopes; and template parameter scopes.

A block scope is introduced by a compound statement, by each selection and iteration statement, and by each exception handler. That is why a variable declared in the condition of an `if`, or in the init-statement of a `for`, is local to the whole statement, including the `else` branch.

The vocabulary changed in C++23. P1787R6, "Declarations and where to find them", rewrote these rules in terms of a declaration **inhabiting** a scope, having a **target scope**, and **binding** a name there. The aim was to fix long-standing defects and inconsistencies while keeping almost all existing code meaning the same thing, and compilers treat most of its fixes as applying to earlier modes too. One related change is visible: P2036R3, adopted for C++23 as a defect report, made a lambda's trailing return type see its own init-captures.

```cpp
#include <type_traits>

void lambda_scope() {
  int x = 0;
  auto f = [x = 2.5]() -> decltype(x) { return x; };  // decltype(x) names the capture
  static_assert(std::is_same_v<decltype(f()), double>);  // passes with GCC 16 and Clang 21
  (void)x;
}
```

## Point of declaration

A name becomes visible at its **locus**, the point of declaration, and the precise location surprises people. For a variable, the locus is immediately after the complete declarator and *before* the initializer. So the declarator still sees the outer name, but the initializer already sees the new one.

```cpp
#include <cstdio>

const int n = 4;

int main() {
  char n[n] = {};                    // array bound uses the outer n: a char[4]
  const int k = 10;
  {
    enum { k = k + 5, m = k * 2 };   // enumerator k is 15, then m is 30
    std::printf("%zu %d %d\n", sizeof n, k, m);  // prints 4 15 30
  }
}
```

Enumerators are different from variables: an enumerator's locus is *after* its initializer, so `k + 5` still reads the outer `k`, while the following `m = k * 2` sees the new enumerator. For a variable, `int v = v;` initializes `v` from itself, so the initializer reads the object's own indeterminate value, which is undefined behavior in C++23.

Other loci worth knowing: a class name is visible right after its name in the class head, so it can appear in its own base-class list, as in CRTP; an alias declaration's name becomes visible only after its type, so `using T = T*;` in an inner scope refers to the outer `T` on the right; and a range-`for` variable is visible only after the range expression, so `for (auto x : x)` iterates over the outer `x`.

Class scope is the exception to "declare before use". Inside member function bodies, default member initializers and default arguments, the whole class is visible, including members declared later. The class is said to be complete in those places.

## Block scope and shadowing

A declaration in an inner block hides any declaration of the same name in enclosing scopes, local or not. A hidden namespace-scope name can still be reached with qualification, such as `::level`, but a hidden local variable cannot be named at all.

```cpp
int level = 0;

int depth() {
  int level = 1;
  {
    int level = 2;            // hides both outer levels; -Wshadow warns
    return level + ::level;   // 2 + 0: the middle level cannot be named from here
  }
}
```

Some redeclarations look like shadowing but are ill-formed. [basic.scope.block] forbids a declaration in the outermost block of a function body from reusing a parameter's name, and a declaration in the body of an `if`, `while`, `for` or `switch` from reusing a name declared in its condition or init-statement. The same applies to a handler's parameter and the handler's outermost block.

```cpp
int get();

void f(int p) {
  // int p = 1;                 // ill-formed: same name as a parameter
  if (int x = get()) {
  } else {
    // int x = 2;               // ill-formed: else shares the condition's scope
  }
  for (int i = 0; i < 3; ++i) {
    { int i = 5; (void)i; }     // OK: a nested block may shadow i
  }
  (void)p;
}
```

> **Pitfall.** Shadowing is legal and silent by default. A local named like a member or a global changes what every later use in the block means. Enable `-Wshadow` in GCC or Clang if your codebase does not deliberately rely on it.

## Namespaces: reopening, nesting, aliases

A namespace definition can be repeated any number of times, in any number of files, and each repetition adds members to the same namespace. A member declared inside a namespace can be defined outside it with a qualified name, but only after it has been declared, and only from a namespace that encloses it.

```cpp
namespace store {
  void save();
}
namespace store { void load(); }    // reopens store

void store::save() {}               // OK: declared above, defined from an enclosing scope
// void store::purge() {}           // ill-formed: purge was never declared in store

namespace store::detail { int retries = 3; }  // C++17 nested namespace definition
```

A **namespace alias** gives an existing namespace a second name, as in `namespace fs = std::filesystem;`. An alias can be used anywhere the namespace name could be used in a qualified name, but it cannot be used to reopen the namespace: `namespace fs { ... }` after the alias is ill-formed.

An **unnamed namespace** behaves as if it were a namespace with a unique name, followed by a using-directive for it. Its members are visible throughout the rest of the translation unit and, since C++11, have internal linkage; the translation-units-and-linkage topic covers the linkage side. Because the members are reached through a using-directive, a name in an unnamed namespace and the same name in the enclosing namespace can coexist, and an unqualified use of it is ambiguous.

## Using-directives and the nearest enclosing namespace

A using-directive such as `using namespace lib;` declares nothing. During unqualified lookup, it makes the members of `lib` appear **as if they were declared in the nearest enclosing namespace that contains both the using-directive and `lib`**. That rule, from [namespace.udir], has a consequence people rarely expect.

```cpp
#include <cstdio>

namespace lib { int value() { return 1; } }

namespace app {
  int value() { return 2; }
  int get() {
    using namespace lib;   // lib's members act as if declared in the global namespace
    return value();        // finds app::value first: returns 2
  }
}

int main() { std::printf("%d\n", app::get()); }  // prints 2
```

The directive is written inside `app::get`, but the nearest namespace enclosing both that function and `lib` is the global namespace. So `lib::value` behaves as a global, and lookup finds `app::value` before reaching it. A using-declaration, `using lib::value;`, would instead declare `value` in the block itself and win.

Using-directives are also transitive: if `B` contains `using namespace A;`, then `using namespace B;` makes `A`'s members visible too. Two directives that bring in the same name are not an error by themselves; only an unqualified use of that name is ambiguous.

> **Standardese.** [namespace.udir] says that during unqualified lookup, the names of the nominated namespace appear as if they were declared in the nearest enclosing namespace that contains both the using-directive and the nominated namespace, and that a using-directive does not add any members to the region in which it appears.

## Inline namespaces and ABI versioning

An **inline namespace**, added in C++11, is a nested namespace whose members also behave as members of the enclosing namespace for most purposes: unqualified and qualified lookup, argument-dependent lookup, and explicit specialization or instantiation of its templates through the enclosing namespace's name. The enclosing namespace and the inline namespace are each associated with the other for ADL.

```cpp
namespace lib {
  namespace v1 { struct Config { int a; }; }
  inline namespace v2 { struct Config { int a, b; }; }

  void load(Config) {}   // Config means lib::v2::Config
}

template <class T> struct Traits;
template <> struct Traits<lib::Config> {};  // specializes for lib::v2::Config

namespace lib::inline v3 {}  // C++20 nested inline namespace syntax
```

The point is that the inline namespace's name still appears in the **mangled names** of its members. `lib::load(lib::v2::Config)` is mangled as `_ZN3lib4loadENS_2v26ConfigE` by GCC 16. Source code says `lib::Config`, but the linker sees the version, so code compiled against `v1` and code compiled against `v2` cannot be silently linked together. Standard libraries use this: libstdc++'s C++11 `std::string` is `std::__cxx11::basic_string`, and libc++ puts the whole library in `std::__1`.

The keyword `inline` must be on the first definition of the namespace. Reopening an inline namespace without it is allowed, but Clang warns; making a namespace inline after it was first defined as non-inline is ill-formed. A name declared both in the enclosing namespace and in its inline namespace makes lookup through the enclosing name ambiguous.

## What to remember

- C++23 scopes: global and other namespace scopes, class, enumeration, block, function parameter, lambda and template parameter.
- P1787R6 rewrote the scope and lookup wording for C++23 with little change in meaning; P2036R3 lets a lambda's trailing return type see its captures.
- A variable is visible from just after its declarator, so `char n[n]` uses the outer `n` and `int v = v;` reads itself.
- An enumerator is visible only after its initializer.
- Inner declarations hide outer ones; hidden globals are reachable with `::`, hidden locals are not.
- Redeclaring a parameter in the function's outer block, or a condition variable in the `if` or `else` body, is ill-formed.
- Namespaces can be reopened; aliases cannot reopen them; qualified definitions need a prior declaration.
- A using-directive makes names act as if declared in the nearest namespace enclosing both the directive and the nominated namespace.
- Inline namespace members act as enclosing-namespace members but keep the inline name in their mangled names, which is how libraries version their ABI.

## Concept Map Outline

- **Namespaces and scope:** Where a declaration is visible, and how named, reopenable namespace scopes combine.
  - **Kinds of scope:** Namespace, class, enumeration, block, function parameter, lambda and template parameter.
    - **Block scopes:** Compound statements, each if, switch, loop and handler introduce one.
    - **P1787R6:** C++23 rewording: declarations inhabit and target scopes and bind names.
    - **P2036R3:** A lambda's trailing return type sees its init-captures; applied as a defect report.
  - **Point of declaration:** The locus where a name starts to be visible.
    - **Variables:** After the declarator, before the initializer: char n[n] uses the outer n.
    - **Enumerators:** After the initializer, so k = k + 5 reads the outer k.
    - **Complete-class contexts:** Member function bodies and default arguments see members declared later.
  - **Block scope:** Inner declarations hide outer ones of the same name.
    - **Shadowing:** Legal and silent; hidden globals are reachable with ::, hidden locals are not.
    - **Forbidden redeclarations:** Parameters in the outer body block, condition names in if or else bodies.
    - **-Wshadow:** GCC and Clang warn about shadowing only when asked.
  - **Namespaces:** Named scopes that can be reopened in any file.
    - **Qualified definitions:** Define a member outside only after declaring it, from an enclosing namespace.
    - **Nested definitions:** namespace a::b::c is C++17; namespace a::inline b is C++20.
    - **Aliases:** namespace fs = std::filesystem; an alias cannot reopen the namespace.
    - **Unnamed namespaces:** A unique name plus a using-directive; same-named globals become ambiguous.
  - **Using-directives:** using namespace N declares nothing; it only changes unqualified lookup.
    - **Nearest enclosing rule:** Names act as if declared in the nearest namespace enclosing directive and target.
    - **Transitive:** A directive for B also brings in namespaces that B nominates.
    - **Ambiguity on use:** Two directives bringing the same name only fail when it is used unqualified.
  - **Inline namespaces:** Members act as members of the enclosing namespace for most purposes.
    - **ABI versioning:** The inline name stays in mangled names, like std::__cxx11 and std::__1.
    - **Specialization:** Templates can be specialized through the enclosing namespace's name.
    - **First definition:** inline must appear on the first definition; adding it later is ill-formed.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.scope.block], [stmt.select])

Is this function well-formed?

```cpp
int get();

void f() {
  if (int x = get()) {
    (void)x;
  } else {
    int x = 2;
    (void)x;
  }
}
```

A. Well-formed: the `else` block is a new scope, so its `x` shadows the condition's `x`
B. Ill-formed: `x` from the condition cannot be redeclared in the outermost block of the `else` branch
C. Well-formed, but the `else` branch reads the condition's `x`
D. Ill-formed: a variable cannot be declared in an `if` condition

**Answer (B):** Ill-formed: `x` from the condition cannot be redeclared in the outermost block of the `else` branch

**Why:** The condition's `x` belongs to the block scope of the whole `if` statement, which encloses both branches. [basic.scope.block] makes it ill-formed for a declaration in the outermost block of a substatement, such as either branch, to redeclare a name from that enclosing condition. The shadowing answer would be right one level deeper: a nested block `{ int x = 2; }` inside the `else` branch is allowed.

### Question 2 [warmup] ([basic.scope.block], [basic.lookup.unqual], [namespace.qual])

What does `main` return?

```cpp
int level = 0;

int depth() {
  int level = 1;
  {
    int level = 2;
    return level + ::level;
  }
}

int main() { return depth(); }
```

A. 3, because `::level` names the enclosing local
B. 1
C. 2
D. Ill-formed: `level` is redeclared in a nested block

**Answer (C):** 2

**Why:** The innermost `level` is 2, and `::level` is qualified lookup in the global namespace, which finds the global `level` with value 0, so `depth` returns 2. `::` never refers to an enclosing block; once the middle `level` is hidden, there is no way to name it. Redeclaring a name in a nested block is ordinary shadowing, which is legal, although `-Wshadow` warns about it.

### Question 3 [warmup] ([namespace.def], [namespace.alias])

Is this translation unit well-formed?

```cpp
namespace very_long_name { int a; }
namespace v = very_long_name;
namespace v { int b; }
```

A. Well-formed: it adds `b` to `very_long_name`
B. Well-formed: it defines a new namespace `v` that hides the alias
C. Ill-formed: a namespace alias cannot be used to reopen a namespace
D. Ill-formed: aliases may only name nested namespaces

**Answer (C):** Ill-formed: a namespace alias cannot be used to reopen a namespace

**Why:** A namespace definition that reopens a namespace must name the namespace itself, not an alias, and `v` already names an alias in this scope, so it cannot also be a new namespace. GCC and Clang both reject the third line. The first option is the tempting one, because an alias works everywhere else a namespace name does, such as in `v::a`.

### Question 4 [tricky] ([basic.scope.pdecl])

What does this program print?

```cpp
#include <cstdio>

const int n = 4;

int main() {
  char n[n] = {};
  const int k = 10;
  {
    enum { k = k + 5, m = k * 2 };
    std::printf("%zu %d %d\n", sizeof n, k, m);
  }
}
```

A. `4 15 30`
B. `4 5 10`, because the enumerator `k` starts at zero
C. Nothing: `char n[n]` is ill-formed because `n` is used in its own declarator
D. `4 15 20`, because `m` uses the outer `k`

**Answer (A):** `4 15 30`

**Why:** A variable's point of declaration is just after its complete declarator, so the bound in `char n[n]` still sees the global `n` with value 4. An enumerator's point of declaration is after its initializer, so `k + 5` reads the local `const int k`, giving 15, and `m = k * 2` then sees the new enumerator, giving 30. The "ill-formed" option assumes a name is visible as soon as it is spelled, which is true for the initializer but not for the declarator.

### Question 5 [tricky] ([namespace.udir], [basic.lookup.unqual])

What does this program print?

```cpp
#include <cstdio>

namespace lib { int value() { return 1; } }

namespace app {
  int value() { return 2; }
  int get() {
    using namespace lib;
    return value();
  }
}

int main() { std::printf("%d\n", app::get()); }
```

A. `1`, because the using-directive is in the innermost scope
B. Nothing; the call is ambiguous between `lib::value` and `app::value`
C. `2`
D. Nothing; a using-directive is not allowed inside a function

**Answer (C):** `2`

**Why:** During unqualified lookup, a using-directive makes the nominated names appear as if declared in the nearest enclosing namespace that contains both the directive and the nominated namespace. Here that is the global namespace, so `lib::value` behaves like a global and is hidden by `app::value`, which lookup reaches first. The first option treats the directive like a using-declaration; `using lib::value;` in the function would indeed return 1.

### Question 6 [tricky] ([namespace.unnamed], [namespace.udir], [basic.lookup.unqual])

Is this translation unit well-formed?

```cpp
namespace { int counter = 0; }
int counter = 1;

int read() { return counter; }
```

A. Ill-formed: the second line redefines `counter`
B. Well-formed: `read` returns 1, because the global declaration hides the unnamed one
C. Well-formed: `read` returns 0, because the unnamed namespace is searched first
D. Ill-formed: the use of `counter` in `read` is ambiguous

**Answer (D):** Ill-formed: the use of `counter` in `read` is ambiguous

**Why:** An unnamed namespace behaves like a uniquely named namespace followed by a using-directive for it. The global `counter` is a different entity from the one in the unnamed namespace, so the first two lines are fine. In `read`, the using-directive makes the unnamed namespace's `counter` appear as if declared in the global namespace, next to the global `counter`, and the unqualified use is ambiguous. `::counter` does compile and names the global one, because qualified lookup consults using-directives only when the namespace has no such member itself; the unnamed namespace's `counter` then cannot be named from outside that namespace at all.

### Question 7 [standardese] ([namespace.udir], [basic.lookup.general])

Which numbered line makes this translation unit ill-formed?

```cpp
namespace A { int n = 1; }
namespace B { int n = 2; }

using namespace A;                  // (1)
using namespace B;                  // (2)
int first() { return A::n; }        // (3)
int second() { return n; }          // (4)
```

A. (2), because it brings in a second `n`
B. (4)
C. (3), because `A::n` is hidden by the directives
D. None; the most recent directive wins

**Answer (B):** (4)

**Why:** [namespace.udir] says a using-directive adds no members to the scope where it appears; it only affects unqualified lookup. Two directives that bring in the same name are therefore not a conflict by themselves. The ambiguity is only diagnosed when an unqualified use finds both `A::n` and `B::n`, which happens in (4) and makes it ill-formed. The qualified `A::n` in (3) is unaffected.

### Question 8 [standardese] ([namespace.def], [basic.lookup.argdep])

Given `namespace lib { inline namespace v2 { struct Config {}; } }`, which statement is true?

A. `lib::Config` names the type, and its members' mangled names under the Itanium ABI still contain `v2`
B. `lib::Config` names the type, and its mangled names are identical to those of a `Config` declared directly in `lib`
C. A template in `lib::v2` cannot be explicitly specialized using the name `lib::`
D. For an argument of type `lib::v2::Config`, ADL searches `lib::v2` but not `lib`

**Answer (A):** `lib::Config` names the type, and its members' mangled names under the Itanium ABI still contain `v2`

**Why:** Members of an inline namespace can be used in most respects as members of the enclosing namespace: lookup, explicit specialization through the enclosing name, and ADL, where the enclosing namespace is associated as well. The inline namespace is still a real namespace, so it appears in the entity's name and therefore in mangled names, so GCC 16 mangles a function `lib::load(lib::Config)` as `_ZN3lib4loadENS_2v26ConfigE`. That is the whole point of using inline namespaces for ABI versioning, and why the second option is wrong.

# C++20 Modules

> Replace fragile textual header graphs with semantic module interfaces, controlled exports, module linkage, and clean boundaries around legacy headers.

- **Source:** C++ Atlas (https://cppatlas.com/topics/modules)
- **Track:** Program structure
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [module.unit] (https://eel.is/c++draft/module.unit), [module.interface] (https://eel.is/c++draft/module.interface), [module.import] (https://eel.is/c++draft/module.import), [module.global.frag] (https://eel.is/c++draft/module.global.frag), [module.private.frag] (https://eel.is/c++draft/module.private.frag), [module.reach] (https://eel.is/c++draft/module.reach), [basic.link] (https://eel.is/c++draft/basic.link)
- **cppreference links:** [Modules](https://en.cppreference.com/w/cpp/language/modules), [identifier with special meaning: module](https://en.cppreference.com/w/cpp/identifier_with_special_meaning/module), [identifier with special meaning: import](https://en.cppreference.com/w/cpp/identifier_with_special_meaning/import), [keyword: export](https://en.cppreference.com/w/cpp/keyword/export), [Translation-unit-local entities](https://en.cppreference.com/w/cpp/language/tu_local)
- **Prerequisites:** translation-units-and-linkage, name-lookup-and-adl

Traditional C++ headers rely on phase 4 textual splicing: every `#include` pastes raw tokens into every consumer translation unit, causing macro leakage in both directions, order-dependent compiles, and quadratic build times. **C++20 modules** replace textual inclusion with semantic translation units compiled once into binary module interfaces (BMIs) and consumed via `import`.

## How modules replace textual inclusion

When a module interface unit is compiled, the compiler emits an interface representation describing only its exported API and reachable entities. Importers read that binary summary directly without re-parsing implementation bodies or legacy headers.

Three isolation guarantees follow immediately from compiling modules semantically rather than textually:

- **Macros never cross `import`.** Preprocessor `#define` directives inside a module interface unit stay strictly inside that unit; importers never inherit them, and macros defined by the importer never alter an already-compiled module.
- **Order independence.** Unlike `#include "a.hpp"` followed by `#include "b.hpp"`, importing named modules in any order produces identical symbol lookup.
- **Private helpers stay hidden.** Non-exported helper functions, constants, and `using namespace` directives inside a module never pollute an importer's namespace.

> **Mental model.** A `#include` copies source code before parsing; a module `import` loads an already-parsed semantic interface. Preprocessor state stops at the module boundary.

## Anatomy of a module unit

A **module unit** (`[module.unit]`) is any translation unit containing a `module-declaration`. Its source layout follows a strict three-zone sequence:

1. **Global module fragment (`module;`):** An optional preamble before the module declaration. Under `[module.global.frag]`, this region may contain *only* preprocessor directives (`#include`, `#define`, `#if`). Legacy headers included here belong to the global module rather than the named module, keeping their C/C++ linkage untouched.
2. **Module purview (`export module name;` or `module name;`):** Everything between the module declaration and an optional private fragment is attached to the named module. Names introduced here carry module ownership and cannot be redeclared identically in another module.
3. **Private module fragment (`module :private;`):** An optional tail inside a *primary module interface unit* (`[module.private.frag]`) when no separate implementation units exist. Declarations after `module :private;` remain invisible and unreachable to importers—useful for single-file libraries, though compiler support varies (`clang++` implements it today, whereas GCC 16 still rejects `module :private;`, making separate `module name;` implementation units more portable).

| Module unit kind | Opening declaration | Emits BMI? | Purpose |
| --- | --- | --- | --- |
| Primary module interface | `export module M;` | Yes | Defines the public exported surface of module `M` |
| Module implementation unit | `module M;` | No | Defines declarations promised by `M` without adding exports |
| Module partition interface | `export module M:part;` | Yes | Splits large interface `M`; must be `export import :part;` |
| Internal partition | `module M:impl;` | Yes | Shares internal helpers across `M` without re-exporting |
| Header unit | `import <vector>;` | Yes | Wraps a legacy header as a precompiled semantic unit with macros |

## Visibility versus reachability

One of the deepest design insights of C++20 modules is the separation between **visibility** (`[module.interface]`) and **reachability** (`[module.reach]`). Adding `export` to a declaration makes its *name* visible to ordinary lookup in importing translation units. However, an entity that is **not** exported can still be **reachable** if an exported declaration refers to it in its return type, parameter type, or template argument.

When a type is reachable but not visible, importers cannot spell the type's name directly, yet they can still receive objects via `auto`, inspect member functions, invoke operators, and use `decltype` on expressions of that type.

```cpp
// File: math_core.cppm (module partition interface)
export module math:core;

export int square(int n) {
    return n * n;
}
```

```cpp
// File: math.cppm (primary module interface)
module;
#include <string> // Global module fragment: keeps <string> out of module purview

export module math;
export import :core; // Re-exports math:core so importers see square()

struct SecretHandle { // Not exported: invisible by name, yet reachable via make_handle()
    int value = 7;
    int read() const { return value; }
};

export SecretHandle make_handle() {
    return {};
}

export std::string greet(const std::string& who);
```

```cpp
// File: math_impl.cpp (module implementation unit)
module;
#include <string>

module math; // Implicitly imports primary module interface math

std::string greet(const std::string& who) {
    return "hi, " + who;
}
```

```cpp
// File: main.cpp (consumer)
import math;

int main() {
    auto handle = make_handle(); // Legal: SecretHandle is reachable via auto
    // SecretHandle raw;         // Error: SecretHandle is not visible to lookup
    return square(3) + handle.read() - 16;
}
```

Notice that `module math;` inside an implementation unit implicitly imports the primary module interface `math`, so `math_impl.cpp` can implement `greet` while seeing `SecretHandle` and all non-exported module-purview helpers.

> **Standardese.** Under `[module.reach]`, a declaration is reachable from an importer whenever an exported declaration exposes its type, base class, or template specialization—even if the declaration itself omits `export`. Lookup visibility requires `export`, whereas semantic completeness (member access, overload checks, destruction) requires only reachability.

## Module linkage and TU-local exposure

Because a named module can span multiple implementation units and internal partitions, C++20 introduced **module linkage** (`[basic.link]`). A non-exported namespace-scope function, class, or variable declared inside a module purview (outside unnamed namespaces and without `static`) has module linkage: every translation unit belonging to module `M` shares that single entity, while all external modules and non-module code cannot link against it.

By contrast, declaring a helper `static` or placing it inside `namespace { ... }` gives it **internal linkage**, making it a **translation-unit-local (TU-local)** entity (`[basic.link]`). Exposing a TU-local entity inside an exported `inline` function, exported template, or exported variable initializer makes the module **ill-formed** (no diagnostic required in corner cases, though modern compilers actively warn or reject it).

> **Pitfall.** Never `#include` a legacy header *after* `export module M;`. Putting `#include <vector>` inside the module purview attaches every declaration inside `<vector>` to module `M`, breaking linkage when another translation unit includes `<vector>` in the global module. Always place legacy `#include` directives between `module;` and `export module M;`.

> **Pitfall.** Calling a `static` helper or referencing an unnamed-namespace constant from an `export inline` function inside a module interface triggers a TU-local exposure error. Either drop `static` (giving the helper module linkage across your module) or mark it `inline` without internal linkage.

## Partitions, header units, and contextual keywords

Large modules split cleanly using **partitions**: `export module M:core;` defines an interface partition that `M` re-exports via `export import :core;`, while `module M:impl;` defines an internal partition that `M` imports via `import :impl;` without exposing it to callers. Note that external consumers can never write `import M:core;` directly—only units of module `M` can import partitions of `M`.

For incremental migration, C++20 provides **header units** (`import <vector>;` or `import "legacy.hpp";`). Unlike named modules, header units *do* export preprocessor macros defined inside the header, allowing gradual replacement of `#include` lines without breaking macro-heavy libraries. Finally, `module` and `import` are **identifiers with special meaning** (`[lex.name]`), not reserved keywords—existing variables or parameters named `module` or `import` remain valid outside module-declaration and import-declaration positions.

## What to remember

- Place legacy `#include` directives strictly inside the **global module fragment** (`module;`) before `export module M;`.
- Macros and unexported declarations stay inside the module; `export import :part;` re-exports module partitions to importers.
- `export` grants **lookup visibility**, whereas returning or referencing an unexported type makes it **reachable** for `auto`, member calls, and destruction.
- Non-exported module-purview entities have **module linkage** (shared across `M`'s units only); never expose `static` or unnamed-namespace **TU-local** entities from exported inline functions or templates.
- Named modules never export macros, whereas C++20 **header units** (`import <header>;`) preserve exported macros to ease migration.

## Concept Map Outline

- **C++20 Modules:** Replaces textual header inclusion with semantic binary interfaces, explicit exports, and module linkage.
  - **Module Isolation:** Compiles an interface once semantically without leaking preprocessor state or parsing order.
    - **Macro Encapsulation:** Macros defined inside a named module never escape export boundaries to importers.
    - **Order Independence:** Importing named modules in any sequence produces identical lookup and compilation.
  - **Unit Structure:** A module unit transitions from global fragment through module purview to optional private fragment.
    - **Global Module Fragment:** Region between module; and export module M; reserved solely for legacy #include directives.
    - **Module Purview:** All declarations after the module declaration attach to that named module.
    - **Private Module Fragment:** Optional module :private; tail hiding single-TU implementation details from importers.
  - **Visibility vs. Reachability:** Exporting controls name lookup visibility while referenced unexported types stay reachable.
    - **Visible Declarations:** Exported names can be spelled directly by importing translation units.
    - **Reachable Unexported Types:** Return or parameter types omitted from export still work via auto and member access.
  - **Linkage & TU-Local:** Separates module-wide internal sharing from translation-unit-private symbols.
    - **Module Linkage:** Non-exported purview entities share one definition across units of the same module.
    - **TU-Local Exposure:** Exported inline functions and templates must not expose static or unnamed-namespace entities.
  - **Partitions & Header Units:** Supports modular sub-units internally and macro-preserving header imports for migration.
    - **Module Partitions:** Interface and internal partitions split module M and are importable only within M.
    - **Header Units:** Syntactic import <header>; builds a precompiled semantic unit while exporting macros.

## Standardese Quiz Questions

### Question 1 [warmup] ([module.global.frag])

Where must legacy `#include <vector>` directives appear inside a module interface file?

A. Between `module;` and `export module M;` inside the global module fragment.
B. Immediately after `export module M;` inside the module purview.
C. Inside `export { #include <vector> }` so callers receive `std::vector`.
D. Inside `module :private;` at the end of the file.

**Answer (A):** Between `module;` and `export module M;` inside the global module fragment.

**Why:** Including a header after `export module M;` attaches all of its declarations to module M, conflicting with other units that include `<vector>` in the global module. Placing `#include` in the global module fragment (`module;`) keeps those declarations in the global module.

### Question 2 [warmup] ([module.import], [cpp.import])

What happens to a `#define DEBUG_TAG 1` macro written inside a named module interface unit `export module app;`?

A. It leaks to importers if placed after `export module app;`.
B. It is exported only if written as `export #define DEBUG_TAG 1`.
C. It never leaks to importers of `app`, because named modules do not export preprocessor macros.
D. It causes a compile error because `#define` is forbidden inside any module unit.

**Answer (C):** It never leaks to importers of `app`, because named modules do not export preprocessor macros.

**Why:** Named modules expose semantic declarations, never preprocessor state. Unlike `#include` or header units (`import <h>;`), macros defined in a named module never affect importing translation units.

### Question 3 [tricky] ([module.interface], [module.reach])

Given module `demo` below, which statement in `main.cpp` compiles cleanly?

```cpp
// demo.cppm
export module demo;
struct Box { int x = 9; };
export Box make_box() { return {}; }

// main.cpp
import demo;
```

A. Box b = make_box();
B. auto b = make_box(); int y = b.x;
C. export Box b = make_box();
D. Neither `Box` nor `b.x` can be used because `Box` is not exported.

**Answer (B):** auto b = make_box(); int y = b.x;

**Why:** Although `Box` is not exported—making its name invisible to unqualified lookup (`Box b` fails)—`Box` is reachable because exported `make_box()` returns it ([module.reach]). Therefore `auto b = make_box();` and accessing `b.x` are well-formed.

### Question 4 [tricky] ([module.import], [module.unit])

Why does writing `import math:core;` directly inside `main.cpp` (a non-module consumer file) fail to compile?

A. Because module partitions must be named with `::` instead of `:`.
B. Because module partitions can only be imported by translation units belonging to the same module `math`.
C. Because partitions cannot contain exported functions.
D. Because `main.cpp` must declare `module math;` before importing any module.

**Answer (B):** Because module partitions can only be imported by translation units belonging to the same module `math`.

**Why:** Under [module.import], a module-partition import (`import :core;`) has no module name prefix and is valid only inside translation units of the owning module. External consumers import the primary module (`import math;`), which uses `export import :core;` to expose interface partitions.

### Question 5 [standardese] ([basic.link], [module.interface])

Why is an `export inline` function inside module `M` ill-formed if it calls a `static` helper function declared in `M`'s purview?

```cpp
export module M;
static int secret() { return 1; }
export inline int api() { return secret(); }
```

A. Because `static` gives `secret` internal linkage (making it TU-local), and an exported inline entity cannot expose TU-local entities.
B. Because `inline` functions are forbidden inside C++20 module interfaces.
C. Because `static` functions in a module purview automatically receive external linkage and clash across units.
D. Because `api()` must be declared `constexpr` to call non-exported helpers.

**Answer (A):** Because `static` gives `secret` internal linkage (making it TU-local), and an exported inline entity cannot expose TU-local entities.

**Why:** In [basic.link], entities with internal linkage (such as namespace-scope `static` functions or unnamed-namespace declarations) are translation-unit-local. Exposing a TU-local entity from a non-TU-local inline function or template is ill-formed; dropping `static` gives `secret()` module linkage instead.

### Question 6 [standardese] ([lex.name], [module.unit])

In `int module = 3; int import = module + 1;` inside a regular function body, how does the lexer classify `module` and `import`?

A. Syntax error, because `module` and `import` became hard keywords in C++20.
B. Valid only when compiled without `-std=c++20`.
C. Valid only if placed inside `module :private;`.
D. Valid identifiers, because `module` and `import` are identifiers with special meaning only in module/import directive positions.

**Answer (D):** Valid identifiers, because `module` and `import` are identifiers with special meaning only in module/import directive positions.

**Why:** To preserve backward compatibility with existing C++ codebases using `module` or `import` as variable, parameter, or field names, C++20 made them identifiers with special meaning ([lex.name]) recognized only at the start of module-declarations and import-declarations.

# The preprocessor and translation phases

> Before any C++ is parsed, source text passes through splicing, tokenization and macro expansion. The preprocessor works on tokens, knows nothing of scopes or types, and follows a handful of exact rules that explain almost every macro surprise.

- **Source:** C++ Atlas (https://cppatlas.com/topics/preprocessor-and-translation-phases)
- **Track:** Program structure
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [lex.phases] (https://eel.is/c++draft/lex.phases), [lex.pptoken] (https://eel.is/c++draft/lex.pptoken), [lex.digraph] (https://eel.is/c++draft/lex.digraph), [cpp.include] (https://eel.is/c++draft/cpp.include), [cpp.cond] (https://eel.is/c++draft/cpp.cond), [cpp.replace] (https://eel.is/c++draft/cpp.replace), [cpp.stringize] (https://eel.is/c++draft/cpp.stringize), [cpp.concat] (https://eel.is/c++draft/cpp.concat), [cpp.rescan] (https://eel.is/c++draft/cpp.rescan), [cpp.predefined] (https://eel.is/c++draft/cpp.predefined), [cpp.embed] (https://eel.is/c++draft/cpp.embed)
- **cppreference links:** [Phases of translation](https://en.cppreference.com/w/cpp/language/translation_phases), [Preprocessor](https://en.cppreference.com/w/cpp/preprocessor), [Replacing text macros](https://en.cppreference.com/w/cpp/preprocessor/replace), [Conditional inclusion](https://en.cppreference.com/w/cpp/preprocessor/conditional), [Source file inclusion](https://en.cppreference.com/w/cpp/preprocessor/include), [Alternative operator representations](https://en.cppreference.com/w/cpp/language/operator_alternative), [Feature testing](https://en.cppreference.com/w/cpp/feature_test)
- **Prerequisites:** translation-units-and-linkage

## The one idea

A C++ compiler does not read your program as C++ straight away. The standard describes translation as nine phases applied in order, and the first four turn bytes into a stream of *preprocessing tokens* with every directive executed and every macro expanded. Only in phase 7 does anything know about declarations, scopes or types.

That ordering explains the preprocessor's character. A macro is a rewrite rule on tokens. It cannot see a namespace, cannot tell a type from a variable, and runs before the compiler could object. Most macro bugs come from expecting it to know something that, at phase 4, does not exist yet.

> **Mental model.** Bytes become characters, characters become tokens, tokens get rewritten, and only then does C++ begin. When a macro does something odd, ask which phase you are in and what that phase can see.

## The nine phases

The phases are a model; real compilers fuse them, but must behave as if they ran in this order.

```text
1  map the file to characters      UTF-8 must be supported (C++23); trigraphs gone (C++17)
2  splice lines                    backslash + newline is deleted
3  tokenize                        preprocessing tokens; each comment becomes one space
4  preprocess                      directives, macro expansion, _Pragma, #include recursion
5  literal encodings               adjacent string literals agree on one encoding prefix
6  concatenate string literals     "a" "b" becomes "ab"
7  compile                         tokens are parsed and analyzed as a translation unit
8  instantiate templates           instantiation units are produced
9  link                            translation units and libraries form a program
```

Phase 2 deletes every backslash that is followed by a newline, joining two physical lines into one logical line. Since C++23 the standard also allows whitespace between the backslash and the newline, which GCC and Clang had long accepted. Splicing happens before comments are recognized, so a `//` comment ending in a backslash swallows the next line.

```cpp
int main() {
  int x = 1;
  // add one to x \
  x = x + 1;
  return x;   // returns 1: the assignment was part of the comment
}
```

Phase 3 forms tokens and replaces each comment with a single space, which is why `/**/` cannot glue two identifiers together. A raw string literal is the one place where splicing is undone: between its quotes, the characters are exactly what you typed.

Because `#include` reruns phases 1 to 4 on the included file, and phase 4 ends by deleting all directives, a header's macros are part of the including file's phase 4 state. That is the property modules deliberately remove; the modules topic covers what `import` does instead.

## Tokenization: maximal munch

Phase 3 cuts the text greedily: the next preprocessing token is the longest sequence of characters that could form one, even if a shorter choice would have let the program compile.

```cpp
int a = 5, b = 2;
int c = a---b;        // a-- - b: c is 3, a becomes 4
// int d = a+++++b;   // a++ ++ + b: error, a++ is not an lvalue
// int e = 0xE+1;     // one pp-number "0xE+1": error, not a valid literal
```

The last line is the subtle one. A *pp-number* may contain `e+` or `E+` because floating literals such as `1e+5` need it, so `0xE+1` is a single token. Spaces around the `+` fix it.

There are a few deliberate exceptions to greed. Header names such as `<vector>` are only formed after `#include`, after `import`, and inside `__has_include`, so `a<b>c` stays three tokens in ordinary code. The sequence `<::` is not read as the digraph `<:` followed by `:` unless the next character is `:` or `>`, which is why `std::vector<::std::string>` works since C++11. And when `>>` closes two template argument lists, the parser splits it, so `std::vector<std::vector<int>>` is fine since C++11 while `X<(6>>1)>` still needs its parentheses.

The *digraphs* `<:` `:>` `<%` `%>` `%:` and `%:%:` are full tokens spelling `[` `]` `{` `}` `#` and `##`, so `%:define` is a directive. The alternative tokens `and`, `or`, `not`, `bitand`, `xor_eq` and the rest are also tokens in their own right, not macros, so `#define and &&` is ill-formed.

## How macros expand

An object-like macro is replaced by its replacement list. A function-like macro is replaced only when its name is followed by `(`, so `(max)(a, b)` calls a function named `max` even when a `max` macro exists.

For a function-like invocation the preprocessor works in a fixed order:

1. Collect the arguments, splitting on commas that are not inside parentheses. Braces and angle brackets do not protect commas, so `F(std::pair<int, int>)` passes two arguments.
2. For each parameter, substitute the argument. If the parameter is an operand of `#` or `##`, the argument is used as written; otherwise it is fully macro-expanded first.
3. Apply `#`, which turns an argument into a string literal, and `##`, which pastes two tokens into one. Pasting must produce a valid token.
4. Rescan the result, together with the rest of the file, for more macros to expand.

```cpp
#define STR(x) #x
#define XSTR(x) STR(x)
#define N 42

const char* a = STR(N);    // "N": the operand of # is not expanded
const char* b = XSTR(N);   // "42": N is expanded before STR sees it
```

> **Standardese.** [cpp.rescan] stops recursion. While a macro's replacement is being rescanned, its own name is not replaced again, and any instance of the name found during that time is marked so it is never replaced later either. Compiler writers call such a token "painted blue".

So `#define x (x * 2)` after a variable `int x = 10;` makes `x` mean `(x * 2)`, which evaluates to 20, rather than recursing forever. Mutual recursion stops the same way: with `#define a b` and `#define b a`, the name `a` expands to `b`, which expands to `a`, which is now painted and stays `a`.

> **Pitfall.** Macro arguments are substituted as tokens, not values. `#define SQUARE(v) v * v` turns `SQUARE(1 + 2)` into `1 + 2 * 1 + 2`, which is 5. Parenthesize every parameter and the whole replacement, and remember that an argument with side effects is evaluated once per use.

Variadic macros take `...` and refer to the extra arguments as `__VA_ARGS__`. C++20 added `__VA_OPT__(tokens)`, which expands to its tokens only when the variable arguments are present, replacing the GNU `, ## __VA_ARGS__` trick.

```cpp
#include <cstdio>
#define LOG(fmt, ...) std::printf(fmt __VA_OPT__(,) __VA_ARGS__)

int main() {
  LOG("start\n");          // std::printf("start\n")
  LOG("%d %d\n", 1, 2);    // std::printf("%d %d\n", 1, 2)
}
```

## `#include` and conditional inclusion

`#include <h>` searches implementation-defined places for a header, which need not be a file. `#include "h"` searches in another implementation-defined way, usually starting beside the current file, and falls back to the `<h>` search. A third form, `#include TOKENS`, macro-expands its tokens first and then must match one of the other two.

`#if` and `#elif` evaluate an integer constant expression with a few special rules. `defined X` and `defined(X)` test for a macro. After macro expansion, every identifier that remains is replaced by `0`, including keywords, except `true` and `false`, which become 1 and 0. The arithmetic is done in `std::intmax_t` and `std::uintmax_t`, so ordinary conversions apply at that width.

```cpp
#if UNDEFINED_NAME == 0   // true: a stray identifier is 0, not an error
#endif
#if -1 < 0u               // false: -1 converts to the largest uintmax_t value
#endif
```

`__has_include(<optional>)` (C++17) reports only whether a header can be found, not whether including it in the current mode works. `__has_cpp_attribute(nodiscard)` (C++20) yields a nonzero date when the attribute is supported. C++23 added `#elifdef`, `#elifndef` and `#warning`.

## `#embed` (C++26)

C++26 adopted `#embed`, which C23 introduced. It expands to a comma-separated list of integer literals, one per byte of a resource, so binary data can initialize an array without an external generator. The resource is found like an `#include` file. Parameters such as `limit(n)`, `prefix(...)`, `suffix(...)` and `if_empty(...)` shape the result, and `__has_embed` reports whether a resource exists and whether it is empty.

```cpp
// with -std=c++26, and data.bin beside this file
static const unsigned char blob[] = {
#embed "data.bin"
};
```

GCC 16 implements it, together with the feature-test macro `__cpp_pp_embed`.

## Predefined and feature-test macros

[cpp.predefined] fixes a short list. `__cplusplus` is `201103L`, `201402L`, `201703L`, `202002L` and `202302L` for C++11 through C++23; GCC 16 reports a provisional `202400L` in C++26 mode. `__FILE__`, `__LINE__`, `__DATE__`, `__TIME__`, `__STDC_HOSTED__` and `__STDCPP_DEFAULT_NEW_ALIGNMENT__` are always defined, and `__STDCPP_THREADS__` is defined when the program can have more than one thread. Defining or undefining any of them is undefined behavior.

`__func__` is not on that list. It is a function-local variable created in phase 7, so `#ifdef __func__` is false, and stringizing it yields the string `"__func__"` rather than the function's name. C++20's `std::source_location` is the type-safe successor to `__FILE__` and `__LINE__`.

Feature-test macros describe what the implementation supports. Language features use names like `__cpp_concepts` and are predefined; library features use names like `__cpp_lib_format` and come from `<version>` or the relevant header. Their values are the year and month of the paper that last changed the feature, so you test with `>=`.

```cpp
#include <version>
#if defined(__cpp_lib_print) && __cpp_lib_print >= 202207L
#include <print>
#endif
```

> **Pitfall.** Feature-test macros say what the compiler claims, per translation unit and per mode. A library compiled in C++17 and a client compiled in C++23 can see different answers in the same header, which is a quick route to an ODR violation.

## What to remember

- Nine phases, in order; macros run in phase 4, so they cannot see types, scopes or templates.
- Line splicing precedes comment recognition: a `//` comment ending in a backslash eats the next line; raw strings undo splicing.
- Tokenization is greedy: `a+++++b` fails, `0xE+1` is one pp-number; `<::` and template `>>` are deliberate exceptions.
- Arguments are fully expanded before substitution, except as operands of `#` and `##`; hence the `XSTR(STR(x))` idiom.
- A macro is never re-expanded inside its own expansion, and painted tokens stay unexpanded forever.
- In `#if`, leftover identifiers are 0, `true` is 1, and arithmetic is in `intmax_t` or `uintmax_t`.
- `__VA_OPT__` is C++20; `#elifdef`, `#elifndef` and `#warning` are C++23; `#embed` is C++26.
- `__func__` is a variable, not a macro.
- Test library features through `<version>` and compare with `>=`.

## Concept Map Outline

- **Preprocessor and phases:** Nine translation phases; macros rewrite tokens in phase 4, before any C++ meaning exists.
  - **Early phases:** Phases 1 to 3 turn bytes into preprocessing tokens.
    - **Phase 1 mapping:** UTF-8 input must be supported since C++23; trigraphs were removed in C++17.
    - **Phase 2 splicing:** Backslash then newline is deleted; C++23 allows whitespace in between.
    - **Comment splice trap:** A // comment ending in a backslash swallows the next line.
    - **Raw strings:** Line splicing is reverted between the quotes of a raw string literal.
  - **Tokenization:** Phase 3 takes the longest possible preprocessing token each time.
    - **Maximal munch:** x+++++y is x++ ++ + y and fails; 0xE+1 is a single invalid pp-number.
    - **Exceptions:** <:: before a non-colon is < then ::, and >> may close two template lists (C++11).
    - **Digraphs:** <: :> <% %> %: %:%: are real tokens for [ ] { } # ##.
    - **Comments:** Each comment becomes one space, so it can never paste tokens.
  - **Macro expansion:** Token substitution followed by rescanning, with recursion blocked.
    - **Argument pre-expansion:** Arguments are fully expanded first unless they are operands of # or ##.
    - **# and ##:** # makes a string literal from an argument; ## pastes two tokens into one valid token.
    - **Painted blue:** A macro name met inside its own expansion is never replaced, then or later.
    - **Needs a parenthesis:** A function-like macro name not followed by ( is left alone, as in (max)(a, b).
    - **__VA_OPT__ (C++20):** Expands its tokens only when variadic arguments are present.
  - **Directives:** Inclusion and conditional compilation, evaluated in phase 4.
    - **#include forms:** <h> and "h" search implementation-defined places; a macro form must expand to one of them.
    - **#if arithmetic:** Done in intmax_t or uintmax_t; leftover identifiers are 0, true is 1.
    - **Detection:** __has_include (C++17) and __has_cpp_attribute (C++20) work inside #if.
    - **C++23 additions:** #elifdef, #elifndef and #warning.
    - **#embed (C++26):** Expands a resource's bytes to a comma-separated list of integers.
  - **Predefined macros:** A short standard list plus feature-test macros.
    - **__cplusplus:** 201103L, 201402L, 201703L, 202002L, 202302L for C++11 to C++23.
    - **__func__:** A function-local variable, not a macro; its contents are implementation-defined.
    - **Feature tests:** __cpp_x for language, __cpp_lib_x from <version>; compare with >=.

## Standardese Quiz Questions

### Question 1 [warmup] ([cpp.subst], [cpp.stringize])

What does this program print?

```cpp
#include <cstdio>

#define STR(x) #x
#define XSTR(x) STR(x)
#define N 42

int main() {
  std::puts(STR(N));
  std::puts(XSTR(N));
}
```

A. `42` then `42`
B. `N` then `N`
C. `N` then `42`
D. `42` then `N`

**Answer (C):** `N` then `42`

**Why:** An argument is macro-expanded before substitution unless the parameter is an operand of `#` or `##`. In `STR(N)` the parameter is stringized directly, giving `"N"`. In `XSTR(N)` the parameter is not an operand of `#`, so `N` becomes `42` first, and the inner `STR(42)` then produces `"42"`. Expecting `42` twice is the usual mistake.

### Question 2 [warmup] ([lex.phases], [lex.comment])

What does this program print?

```cpp
#include <cstdio>

int main() {
  int x = 1;
  // add one to x \
  x = x + 1;
  std::printf("%d\n", x);
}
```

A. `2`
B. Nothing: it is ill-formed because a comment cannot end in a backslash
C. It is unspecified whether it prints `1` or `2`
D. `1`

**Answer (D):** `1`

**Why:** Line splicing happens in phase 2 and comments are recognized in phase 3. The backslash at the end of the comment line joins it with the next line, so `x = x + 1;` becomes part of the `//` comment and never executes. GCC warns about a multi-line comment, but the program is well-formed and prints `1`.

### Question 3 [warmup] ([lex.pptoken], [expr.post.incr])

Is this program well-formed?

```cpp
int main() {
  int x = 1, y = 2;
  int z = x+++++y;
  return z;
}
```

A. Well-formed: it parses as `x++ + ++y`, so `z` is 4
B. Ill-formed: it tokenizes as `x ++ ++ + y`, and `x++` is not an lvalue
C. Undefined behavior: `x` and `y` are modified without sequencing
D. Well-formed: it parses as `x + ++(++y)`

**Answer (B):** Ill-formed: it tokenizes as `x ++ ++ + y`, and `x++` is not an lvalue

**Why:** Tokenization is greedy: each preprocessing token is the longest sequence that could be one, regardless of whether the parse then succeeds. So the five pluses become `++`, `++`, `+`. The expression is `(x++)++ + y`, and the outer increment needs an lvalue, which the prvalue `x++` is not. Writing `x++ + ++y` with spaces gives the intended meaning.

### Question 4 [tricky] ([cpp.cond])

What does this program print? `UNDEFINED_NAME` is not defined anywhere.

```cpp
#include <cstdio>

int main() {
#if -1 < 0u
  std::puts("less");
#else
  std::puts("not less");
#endif
#if UNDEFINED_NAME == 0
  std::puts("zero");
#endif
}
```

A. `less` then `zero`
B. `not less` then `zero`
C. `less` only
D. Nothing: it is ill-formed because `UNDEFINED_NAME` is not declared

**Answer (B):** `not less` then `zero`

**Why:** In `#if`, unsigned operands behave as `std::uintmax_t`, so `-1` converts to the largest unsigned value and `-1 < 0u` is false. After macro expansion, any remaining identifier other than `true` and `false` is replaced by `0`, so `UNDEFINED_NAME == 0` is true rather than an error. The tempting `less` comes from thinking of the comparison as mathematical integers.

### Question 5 [tricky] ([cpp.rescan])

What does this program print?

```cpp
#include <cstdio>

int a = 1, b = 2;
#define a b
#define b a

int main() { std::printf("%d %d\n", a, b); }
```

A. `1 2`
B. `2 1`
C. Nothing: it is ill-formed because the macros are recursive
D. `2 2`

**Answer (A):** `1 2`

**Why:** While a macro's replacement is rescanned, its own name is not replaced again. In `main`, `a` becomes `b`, which becomes `a`, and that `a` is inside the expansion of `a`, so it stays `a`. Likewise `b` ends up as `b`. The definitions on the line before the `#define`s are untouched because macros only apply after their definition. Expecting a swap to `2 1` assumes only one level of expansion.

### Question 6 [tricky] ([cpp.concat], [cpp.subst], [cpp.rescan])

What does this program print?

```cpp
#include <cstdio>

#define CAT(a, b) a ## b
#define VAL 7
#define VAL2 99

int main() { std::printf("%d\n", CAT(VAL, 2)); }
```

A. `72`
B. `7`
C. Nothing: it is ill-formed because `72` is pasted from two tokens
D. `99`

**Answer (D):** `99`

**Why:** An argument whose parameter is an operand of `##` is substituted as written, not macro-expanded. So the tokens `VAL` and `2` are pasted into the identifier `VAL2`, and rescanning then expands that to `99`. The tempting `72` requires `VAL` to be expanded first, which needs an extra level of indirection, as in `#define XCAT(a, b) CAT(a, b)`.

### Question 7 [standardese] ([dcl.fct.def.general], [cpp.predefined])

Which branch of the conditional is compiled?

```cpp
#include <cstdio>

int main() {
#ifdef __func__
  std::puts("macro");
#else
  std::puts(__func__);
#endif
}
```

A. The `#ifdef` branch: `__func__` is a predefined macro
B. The `#else` branch: `__func__` is a function-local variable, not a macro
C. It is implementation-defined which branch is compiled
D. Neither: `__func__` may not appear in a preprocessing directive

**Answer (B):** The `#else` branch: `__func__` is a function-local variable, not a macro

**Why:** The standard defines `__func__` in [dcl.fct.def.general] as if each function body began with `static const char __func__[] = "function-name";`. It is a variable that exists from phase 7, so the preprocessor knows nothing about it and `#ifdef __func__` is false. The contents of the string are implementation-defined, although GCC and Clang give `main` here. `__FILE__` and `__LINE__` really are macros, which is why the first option is tempting.

### Question 8 [standardese] ([lex.pptoken], [lex.phases], [lex.string])

In C++23, what does this program print? The backslash is the last character on its line.

```cpp
#include <cstdio>
#include <cstring>

int main() {
  const char* s = R"(a\
b)";
  std::printf("%zu\n", std::strlen(s));
}
```

A. `2`, because phase 2 spliced the lines into `ab`
B. `3`, because the backslash and newline form one escape
C. `4`
D. Nothing: the raw string literal is ill-formed

**Answer (C):** `4`

**Why:** Phase 2 does splice the lines, but [lex.pptoken] says that between the quotes of a raw string literal any line splicing is reverted. The literal therefore contains `a`, a backslash, a newline and `b`, and raw strings process no escape sequences. So `strlen` is 4. The answer 2 is what an ordinary string literal written across the same two lines would give.

# Attributes

> Attributes annotate entities and statements with information the compiler may use. Unknown ones are ignored, standard ones in the wrong place are errors, and a few of them are promises that cause undefined behavior when broken.

- **Source:** C++ Atlas (https://cppatlas.com/topics/attributes)
- **Track:** Program structure
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [dcl.attr.grammar] (https://eel.is/c++draft/dcl.attr.grammar), [dcl.attr.nodiscard] (https://eel.is/c++draft/dcl.attr.nodiscard), [dcl.attr.unused] (https://eel.is/c++draft/dcl.attr.unused), [dcl.attr.deprecated] (https://eel.is/c++draft/dcl.attr.deprecated), [dcl.attr.fallthrough] (https://eel.is/c++draft/dcl.attr.fallthrough), [dcl.attr.likelihood] (https://eel.is/c++draft/dcl.attr.likelihood), [dcl.attr.noreturn] (https://eel.is/c++draft/dcl.attr.noreturn), [dcl.attr.nouniqueaddr] (https://eel.is/c++draft/dcl.attr.nouniqueaddr), [dcl.attr.assume] (https://eel.is/c++draft/dcl.attr.assume), [intro.object] (https://eel.is/c++draft/intro.object)
- **cppreference links:** [Attribute specifier sequence](https://en.cppreference.com/w/cpp/language/attributes), [C++ attribute: nodiscard](https://en.cppreference.com/w/cpp/language/attributes/nodiscard), [C++ attribute: noreturn](https://en.cppreference.com/w/cpp/language/attributes/noreturn), [C++ attribute: assume](https://en.cppreference.com/w/cpp/language/attributes/assume), [C++ attribute: no_unique_address](https://en.cppreference.com/w/cpp/language/attributes/no_unique_address), [C++ attribute: fallthrough](https://en.cppreference.com/w/cpp/language/attributes/fallthrough), [C++ attribute: likely, unlikely](https://en.cppreference.com/w/cpp/language/attributes/likely), [C++ attribute: indeterminate](https://en.cppreference.com/w/cpp/language/attributes/indeterminate)
- **Prerequisites:** object-layout-and-alignment, strict-aliasing-and-undefined-behavior

## The one idea

An attribute is a note attached to a declaration, a type or a statement, written in double square brackets. The language promises very little about what any note does. Unknown attributes are ignored, and most standard ones only *encourage* a warning or an optimization.

That makes it easy to forget the exceptions. A few standard attributes are claims you make to the compiler, and the optimizer is entitled to believe them. A `[[noreturn]]` function that returns, or an `[[assume]]` whose expression is false, is undefined behavior. `[[no_unique_address]]` changes the layout of a class.

> **Mental model.** Read every attribute as one of three things: a request for a diagnostic (`nodiscard`, `deprecated`, `maybe_unused`, `fallthrough`), an optimization hint that cannot change meaning (`likely`, `unlikely`), or a promise the program must keep (`noreturn`, `assume`, `indeterminate`). Only the third kind can turn a correct-looking program into undefined behavior. `no_unique_address` is the odd one out: it permits a layout change.

## Syntax and appertainment

An attribute specifier is `[[ ... ]]` holding a comma-separated list. Each attribute is an optionally namespaced name, optionally followed by a parenthesized argument list made of balanced tokens: `[[nodiscard]]`, `[[deprecated("use g")]]`, `[[gnu::always_inline]]`. Since C++17 `[[using gnu: always_inline, hot]]` applies a namespace to every name in the list, and the names inside may then not be namespaced themselves.

Where you write it decides what it *appertains* to:

| Position | Appertains to |
| --- | --- |
| start of a declaration: `[[nodiscard]] int f();` | each entity declared |
| after the declarator-id: `int x [[maybe_unused]];` | that one entity |
| after `class`, `struct`, `union` or `enum`: `struct [[nodiscard]] S` | the class or enumeration |
| after the type specifiers: `int [[vendor::x]] y;` | the type |
| start of a statement: `[[likely]] return 0;` | the statement |
| start of a label: `[[unlikely]] case 3:` | the label |

The table hides a common mistake. An attribute at the start of a declaration appertains to the entities its declarators declare. A class definition with no declarator declares no such entity, so the grammar does not allow the attribute there at all.

```cpp
struct [[nodiscard]] Error { int code; };   // OK: Error is a nodiscard type
// [[nodiscard]] struct Bad { int code; };  // ill-formed; GCC ignores it with a warning,
//                                           // Clang rejects it
```

Lambdas follow the same logic. Before C++23 there was no place to put an attribute that appertains to a lambda's function call operator; C++23 allows one right after the capture list.

```cpp
auto make = [] [[nodiscard]] () { return 42; };   // C++23: appertains to operator()

void demo() {
  make();   // warning: discarded nodiscard result
}
```

One attribute specifier does not use brackets at all. `alignas` is grammatically an attribute specifier too, which is why it can appear in the same positions, but its rules live with alignment rather than here.

## Unknown and misplaced attributes

[dcl.attr.grammar] says an attribute token the implementation does not recognize is ignored. This is what makes vendor attributes portable: GCC ignores `[[msvc::no_unique_address]]`, MSVC ignores `[[gnu::cold]]`, and both compile. Before C++17, the effect of an unrecognized attribute was implementation-defined. Compilers still warn, with `-Wattributes` in GCC and `-Wunknown-attributes` in Clang, and the argument tokens must still be balanced.

Standard attributes get no such latitude. If a standard attribute appears where it may not apply, the program is ill-formed. `[[noreturn]]` on a variable, `[[fallthrough]]` not followed by a case label, and `[[likely, unlikely]]` together are all errors in the standard's eyes, even where GCC only warns.

```cpp
[[acme::fast]] int f();      // ignored: unknown attribute
[[noreturn]] int v;          // ill-formed: noreturn applies only to functions
```

To ask whether an attribute is supported, use `__has_cpp_attribute(name)` inside `#if`. It yields 0 for an unknown attribute and otherwise a date, such as `201907L` for `nodiscard` with a reason string.

## Attributes that ask for a diagnostic

`[[nodiscard]]` (C++17) on a function, or on a class or enumeration type returned by value, asks for a warning when a call's result is discarded. C++20 added a reason string and allowed it on constructors, so `S(1);` as a statement can warn too. A cast to `void` is the sanctioned way to discard.

The type form only covers calls that return the type by value. A function returning a reference to a nodiscard type does not trigger it, because its return type is a reference, not the class.

```cpp
struct [[nodiscard]] Error { int code; };
Error make();
Error& last();

void demo() {
  make();          // warning: discarded nodiscard type
  last();          // no warning: the return type is Error&
  (void)make();    // no warning: explicitly discarded
}
```

> **Standardese.** The standard never makes ignoring a nodiscard result ill-formed. [dcl.attr.nodiscard] puts the warning under "recommended practice", so a conforming compiler may stay silent.

`[[maybe_unused]]` (C++17) suppresses unused warnings for variables, parameters, functions, types, enumerators and structured bindings. `[[deprecated]]` (C++14), optionally with a message, marks a name whose use should warn; it also works on namespaces, enumerators and template specializations.

`[[fallthrough]];` (C++17) is a null statement that documents an intentional fall from one case into the next. The rule is strict: the next statement executed after it must be a statement labelled with a `case` or `default` of the same `switch`. Placing it at the end of the last case is ill-formed.

## Hints that change no meaning

`[[likely]]` and `[[unlikely]]` (C++20) go on a statement or label and say a path is more or less probable. They affect only code layout and branch prediction hints. A path containing a likely label is presumed more probable than one without, and compilers are free to ignore all of it. The two cannot appear on the same statement.

```cpp
int classify(int x) {
  switch (x) {
    [[likely]] case 0: return 1;
    [[unlikely]] case 1: return 2;
    default: return 3;
  }
}
```

`[[no_unique_address]]` (C++20) is not a pure hint, because it lets a non-static data member overlap others, which normally changes `sizeof`. It is still optional: MSVC ignores it for ABI reasons and spells it `[[msvc::no_unique_address]]`. What the standard does guarantee is that two distinct objects of the same type never share an address, even with the attribute.

```cpp
struct Empty {};
struct Pair {
  [[no_unique_address]] Empty a;
  [[no_unique_address]] Empty b;   // same type as a: &p.a != &p.b is guaranteed
  int i;
};
```

## Promises the optimizer believes

`[[noreturn]]` (C++11) says a function never returns to its caller. It may throw, loop forever or end the program, but if control ever returns, the behavior is undefined. The compiler uses the promise to delete code after the call and to silence missing-return warnings. The standard library declares `std::exit`, `std::abort`, `std::terminate` and `std::rethrow_exception` this way, among others. The first declaration of the function must carry the attribute if any declaration does. Within one file that is diagnosed; across files it is ill-formed with no diagnostic required.

```cpp
[[noreturn]] void fail(const char* why);

int parse(int x) {
  if (x < 0) fail("negative");   // compiler may assume this never comes back
  return x;
}
```

`[[assume(expr)]];` (C++23) is a statement that tells the compiler `expr` would be true at that point. The expression is never evaluated, so side effects in it never happen. If it would not evaluate to true, the behavior is undefined. The point is to give the optimizer facts it cannot prove, such as a divisor being positive or a size being a multiple of four, so that it can drop the code for the cases you have ruled out.

```cpp
#include <cstdio>
int main() {
  int i = 0;
  [[assume(++i > 0)]];       // not evaluated: i stays 0
  std::printf("%d\n", i);    // prints 0
}
```

> **Pitfall.** `assert(cond)` checks in debug builds and does nothing under `NDEBUG`. `[[assume(cond)]]` never checks and lets the optimizer delete code that handles the case where `cond` is false. Turning asserts into assumptions for release builds turns every failing assert into undefined behavior.

`[[indeterminate]]` is C++26. C++26 makes reading an uninitialized automatic variable *erroneous behavior*: the variable holds an implementation-chosen value, and reading it is a bug the implementation may diagnose, or even stop the program for, but may not treat as undefined. `[[indeterminate]]` on such a variable, or on a function parameter, opts back into the old rules: the value is indeterminate and reading it is undefined behavior. It exists for performance-critical buffers that are always written before they are read. GCC 16 accepts it with `-std=c++26`; Clang 21 ignores it as unknown. The erroneous behavior rules themselves belong to the C++26 language-changes topic.

## What to remember

- Position decides appertainment; put class attributes after the class key, as in `struct [[nodiscard]] S`.
- Unknown attributes are ignored since C++17; misplaced standard attributes are ill-formed.
- `[[using ns: a, b]]` namespaces a whole list, and the names inside cannot repeat a namespace.
- `nodiscard`, `deprecated`, `maybe_unused` and `fallthrough` only request diagnostics; none makes discarding a result ill-formed.
- `nodiscard` on a type covers by-value returns only.
- `[[fallthrough]];` must be followed by a case or default label of the same switch.
- `likely` and `unlikely` are pure hints; `no_unique_address` may change layout but never merges two objects of one type.
- A `noreturn` function that returns, or an `assume` that is false, is undefined behavior.
- An `assume` expression is never evaluated.
- `[[indeterminate]]` (C++26) opts an uninitialized variable out of erroneous behavior and back into undefined behavior.

## Concept Map Outline

- **Attributes:** Annotations on entities and statements: diagnostic requests, hints, and promises the optimizer may exploit.
  - **Syntax and placement:** Double brackets; the position decides what an attribute appertains to.
    - **Arguments:** An attribute may take a parenthesized list of balanced tokens, as in deprecated("use g").
    - **using prefix (C++17):** [[using gnu: hot, cold]] namespaces a list; the names inside cannot be namespaced again.
    - **Class attributes:** Write struct [[nodiscard]] S; an attribute before struct with no declarator is ill-formed.
    - **Statements and labels:** likely, unlikely and fallthrough attach to statements or labels, not declarations.
  - **Unknown vs misplaced:** Unrecognized attributes are ignored; standard ones used wrongly are errors.
    - **Ignored (C++17):** An unrecognized attribute token is ignored; in C++11 and C++14 this was implementation-defined.
    - **Misplaced standard:** A standard attribute applied where it cannot apply makes the program ill-formed.
    - **__has_cpp_attribute:** Yields 0 if unsupported, otherwise a date such as 201907L for nodiscard.
  - **Diagnostic requests:** They encourage warnings and never make code ill-formed by being violated.
    - **nodiscard:** C++17; reason string and constructors in C++20; type form covers by-value returns only.
    - **deprecated:** C++14; optional message; works on namespaces, enumerators and specializations.
    - **maybe_unused:** C++17; silences unused warnings for variables, functions, types and bindings.
    - **fallthrough:** C++17 null statement; the next statement must carry a case or default label.
  - **Hints and layout:** Optimization information that compilers may ignore.
    - **likely, unlikely:** C++20 path probability hints; both on one statement is ill-formed.
    - **no_unique_address:** C++20; lets a member overlap others, changing sizeof; MSVC ignores it.
    - **Same-type rule:** Two distinct objects of the same type never share an address.
  - **Promises:** Breaking these is undefined behavior, and the optimizer relies on them.
    - **noreturn:** C++11; returning is UB; the first declaration must carry it if any does.
    - **assume (C++23):** The expression is not evaluated; if it would be false, behavior is undefined.
    - **assume vs assert:** assert checks in debug builds; assume never checks and lets code be deleted.
    - **indeterminate (C++26):** Opts an uninitialized variable out of erroneous behavior back into UB on read.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.attr.nodiscard])

In C++23, what does the standard require of a compiler translating `demo`?

```cpp
[[nodiscard]] int compute();

void demo() {
  compute();
}
```

A. It must reject the program: discarding the result is ill-formed
B. It must issue a diagnostic, but may still accept the program
C. Nothing: a warning is only recommended practice
D. Nothing, but calling `demo` is undefined behavior

**Answer (C):** Nothing: a warning is only recommended practice

**Why:** [dcl.attr.nodiscard] only encourages a warning when a nodiscard call's result is discarded; it appears under recommended practice. The program is well-formed, a silent compiler is conforming, and nothing about the call's behavior changes. GCC and Clang do warn, which is why the first two options feel right.

### Question 2 [warmup] ([dcl.attr.grammar])

In C++23, is this program well-formed? No compiler you know of supports `acme::fast`.

```cpp
[[acme::fast]] int f();

int f() { return 1; }

int main() { return f(); }
```

A. Ill-formed: `acme::fast` is not a recognized attribute
B. Well-formed: an unrecognized attribute is ignored
C. Implementation-defined behavior
D. Ill-formed: attribute namespaces other than `gnu`, `clang` and `msvc` are reserved

**Answer (B):** Well-formed: an unrecognized attribute is ignored

**Why:** Since C++17, [dcl.attr.grammar] says an attribute token the implementation does not recognize is ignored, which is what lets vendor attributes appear in portable code. Compilers usually warn, as GCC does with `-Wattributes`. Implementation-defined behavior was the C++11 and C++14 rule for attributes not specified by the standard.

### Question 3 [warmup] ([dcl.attr.assume])

In C++23, what does this program print?

```cpp
#include <cstdio>

int main() {
  int i = 0;
  [[assume(++i > 0)]];
  std::printf("%d\n", i);
}
```

A. `1`
B. Undefined behavior
C. Nothing: an assumption may not have side effects, so it is ill-formed
D. `0`

**Answer (D):** `0`

**Why:** The expression of an assumption is never evaluated, so `++i` never runs and `i` is still 0. There is no undefined behavior, because the expression would be true if it were evaluated. Side effects are allowed in the expression; they are simply discarded, and Clang warns that such an assumption is ignored.

### Question 4 [tricky] ([dcl.pre], [dcl.attr.grammar])

In C++23, what is the effect of this declaration?

```cpp
[[nodiscard]] struct Error { int code; };
```

A. `Error` becomes a nodiscard type, the same as `struct [[nodiscard]] Error`
B. The attribute is ignored because it is in an unrecognized position
C. It is ill-formed: an attribute at the start of a declaration needs a declarator to appertain to
D. The attribute applies to the next function declared

**Answer (C):** It is ill-formed: an attribute at the start of a declaration needs a declarator to appertain to

**Why:** An attribute specifier at the start of a simple declaration appertains to the entities its declarators declare, and the grammar only allows it when there is a declarator list. This declaration has none, so it is ill-formed; the class attribute belongs after the class key, as in `struct [[nodiscard]] Error`. Clang rejects it, while GCC only warns that the attribute is ignored, which makes the second option look right.

### Question 5 [tricky] ([dcl.attr.nodiscard])

Which of the discarded calls in `demo` are nodiscard calls, the ones compilers are encouraged to warn about?

```cpp
struct [[nodiscard]] Error { int code; };

Error make();
Error& last();

void demo() {
  make();
  last();
}
```

A. Both calls
B. Only `make()`
C. Only `last()`
D. Neither: the attribute is on the type, not on the functions

**Answer (B):** Only `make()`

**Why:** A nodiscard call is a call to a function declared nodiscard, or a call whose return type is a class or enumeration type marked nodiscard. `make` returns `Error` by value, so it qualifies. `last` returns `Error&`, a reference type, so the type's attribute does not apply; GCC warns about `make()` only.

### Question 6 [tricky] ([dcl.attr.fallthrough])

In C++23, is this function well-formed?

```cpp
int f(int x) {
  switch (x) {
    case 1:
      ++x;
      [[fallthrough]];
    case 2:
      return x;
    default:
      ++x;
      [[fallthrough]];
  }
  return x;
}
```

A. Well-formed: falling out of the switch is a kind of fall-through
B. Undefined behavior only when the default branch is taken
C. Well-formed, but compilers may warn
D. Ill-formed: the second `[[fallthrough]];` is not followed by a case or default label

**Answer (D):** Ill-formed: the second `[[fallthrough]];` is not followed by a case or default label

**Why:** [dcl.attr.fallthrough] requires the next statement executed after a fallthrough statement to be labelled with a case or default label of the same switch, and makes the program ill-formed if there is no such statement. The first use is fine; the second sits at the end of the switch. Clang rejects it, while GCC only warns, which is a permitted diagnostic but makes the third option tempting.

### Question 7 [standardese] ([dcl.attr.noreturn])

In C++23, is this translation unit well-formed?

```cpp
void stop();
[[noreturn]] void stop();
```

A. Ill-formed: the first declaration must specify `noreturn` if any declaration does
B. Well-formed: attributes accumulate across redeclarations
C. Ill-formed, no diagnostic required
D. Well-formed, and undefined behavior only if `stop` returns

**Answer (A):** Ill-formed: the first declaration must specify `noreturn` if any declaration does

**Why:** [dcl.attr.noreturn] says the first declaration of a function shall specify `noreturn` if any of its declarations does. Within one translation unit that is an ordinary diagnosable rule, and both GCC and Clang reject this. The no-diagnostic-required case is the cross-file one, where a function is declared `noreturn` in one translation unit and without it in another. Many other attributes, such as `deprecated`, may be added on a redeclaration, which is why the second option is tempting.

### Question 8 [standardese] ([intro.object], [dcl.attr.nouniqueaddr])

For an object `p` of type `Pair`, which of these does the C++23 standard guarantee?

```cpp
struct Empty {};

struct Pair {
  [[no_unique_address]] Empty a;
  [[no_unique_address]] Empty b;
  int i;
};
```

A. `sizeof(Pair) == sizeof(int)`
B. `(void*)&p.a == (void*)&p.b`
C. `(void*)&p.a != (void*)&p.b`
D. `sizeof(Pair) > sizeof(int)`

**Answer (C):** `(void*)&p.a != (void*)&p.b`

**Why:** [intro.object] allows two objects with overlapping lifetimes to share an address only if one is nested in the other, or at least one is a zero-size subobject and their types are not similar. `a` and `b` have the same type, so their addresses must differ even though both may be zero-size. Neither size claim is guaranteed: the attribute only permits overlap, and MSVC ignores it entirely.

# Program startup and termination

> Before main runs, every static variable is zero- or constant-initialized and then dynamically initialized in a partly specified order. After it, std::exit unwinds that work in reverse, interleaved with atexit handlers, while quick_exit, abort and terminate each skip different parts.

- **Source:** C++ Atlas (https://cppatlas.com/topics/program-startup-and-termination)
- **Track:** Program structure
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [basic.start.main] (https://eel.is/c++draft/basic.start.main), [basic.start.static] (https://eel.is/c++draft/basic.start.static), [basic.start.dynamic] (https://eel.is/c++draft/basic.start.dynamic), [basic.start.term] (https://eel.is/c++draft/basic.start.term), [stmt.dcl] (https://eel.is/c++draft/stmt.dcl), [support.start.term] (https://eel.is/c++draft/support.start.term), [except.terminate] (https://eel.is/c++draft/except.terminate), [except.handle] (https://eel.is/c++draft/except.handle)
- **cppreference links:** [Main function](https://en.cppreference.com/w/cpp/language/main_function), [Initialization (non-local variables)](https://en.cppreference.com/w/cpp/language/initialization), [Constant initialization](https://en.cppreference.com/w/cpp/language/constant_initialization), [std::exit](https://en.cppreference.com/w/cpp/utility/program/exit), [std::atexit](https://en.cppreference.com/w/cpp/utility/program/atexit), [std::quick_exit](https://en.cppreference.com/w/cpp/utility/program/quick_exit), [std::abort](https://en.cppreference.com/w/cpp/utility/program/abort), [std::terminate](https://en.cppreference.com/w/cpp/error/terminate)
- **Prerequisites:** object-lifetime-and-storage, translation-units-and-linkage, exceptions-and-stack-unwinding

## The one idea

A C++ program does real work before `main` and after it. Before, every variable with static storage duration is initialized, in two phases with different guarantees. After, the objects that were constructed are destroyed in reverse, with functions registered through `std::atexit` slotted into the same reverse sequence.

The rules are sharp at the two extremes and vague in the middle. Static initialization is complete before any dynamic initialization begins. Within one translation unit, ordinary dynamic initialization follows definition order. Across translation units, the order is unspecified, and an implementation may even defer it until first use. On the way out, only `std::exit`, which returning from `main` calls, runs the full teardown. The other exits each skip a different part of it.

> **Mental model.** Startup is a stack being pushed: every completed static initialization, and every `atexit` registration, is pushed in the order it happened. `std::exit` pops the stack. `quick_exit` pops a different, smaller stack, and `abort` throws the stack away.

The object-lifetime-and-storage topic introduces storage durations and the cross-file initialization order fiasco. This topic goes into the phases themselves and into every way a program can end.

## `main` is special

[basic.start.main] gives `main` rules no other function has:

- Its return type must be declared as `int`. `auto main() -> int` is fine; `auto main()` with a deduced type is not.
- It may not be `inline`, `static`, `constexpr`, `consteval`, deleted, or a coroutine. A global variable named `main` is ill-formed, and so is a global function `main` attached to a named module.
- It may not be *used* by the program: no recursive call, no taking its address. GCC accepts both with only a `-Wpedantic` warning.
- Falling off the end is equivalent to `return 0;`. No other value-returning function gets that.
- `argv[argc]` is guaranteed to be a null pointer.

Returning from `main` first destroys `main`'s automatic objects, then calls `std::exit` with the returned value. That one detail separates `return 0;` from `std::exit(0);`, as the termination section shows.

A function-try-block on `main` cannot catch everything that happens around it. Exceptions from constructors of namespace-scope objects and from destructors of static objects happen outside `main`'s body, and [except.handle] says the handler does not see them.

## Static initialization: zero and constant

[basic.start.static] defines the first phase. A variable with static or thread storage duration is *constant-initialized* if its initialization is a constant expression; otherwise it is first *zero-initialized*. These two together are called static initialization, and all of it strongly happens before any dynamic initialization. In practice the values are in the executable image and no code runs.

This is the one cross-file order guarantee you get for free. A constant-initialized variable can be read safely from any dynamic initializer anywhere in the program.

```cpp
// file a.cpp
int f();
int x = f();          // dynamic initialization

// file b.cpp
int y = 5;            // constant initialization: done before any dynamic init
int f() { return y; } // so x is 5, whichever file runs first
```

C++20's `constinit` turns this into a checked promise: the variable must be constant-initialized or the program is ill-formed. Unlike `constexpr`, it does not make the variable `const`.

The standard also lets an implementation turn dynamic initialization into static initialization, as long as the variable ends with the value dynamic initialization would have given it, and no other variable changes before its own initialization. The standard's own example shows the consequence: another variable that reads it early may see either value.

```cpp
inline double fd() { return 1.0; }
extern double d1;
double d2 = d1;     // unspecified: 0.0 if d1 is still zero, 1.0 if d1 was done statically
double d1 = fd();   // dynamic in principle, but may be performed statically
```

GCC and Clang both print 0 for `d2` here, but the standard permits 1.

## Dynamic initialization: three orderings

Everything else is dynamic initialization, and [basic.start.dynamic] sorts non-block variables into three groups:

| Kind | Which variables | Order guarantee |
| --- | --- | --- |
| ordered | ordinary namespace-scope variables and static data members | definition order within one translation unit |
| partially ordered | inline variables that are not template specializations | before a later variable if defined before it in every file that defines that one |
| unordered | static data members of class templates and variable template specializations, unless explicitly specialized | none, even within one file |

Across translation units nothing is ordered. Initializations in different files happen in an unspecified order, and once the program has started a thread, which deferred initialization makes possible, they may even run on different threads.

```cpp
int next_id();

template <class T> struct Tag { static int id; };
template <class T> int Tag<T>::id = next_id();   // unordered

int first = next_id();                            // ordered, but not relative to Tag<T>::id
```

The implementation may also *defer* dynamic initialization until after `main` starts. If it does, a variable is initialized before the first odr-use of any non-inline function or variable defined in its translation unit. Whether that deferral happens is implementation-defined; mainstream toolchains initialize everything before `main`.

> **Pitfall.** Self-registering objects, such as a factory entry created by a namespace-scope constructor, are fragile for a separate reason. If they live in a static library and nothing references their object file, the linker never includes it, and the constructor never runs. That is linker behavior, not a C++ rule, so no language feature fixes it.

If a dynamic initializer of a non-block variable exits with an exception, `std::terminate` is called.

## Block-scope statics

A static local is the standard tool for controlled order. [stmt.dcl] says its dynamic initialization happens the first time control passes through its declaration. Since C++11 that initialization is thread-safe: a concurrent caller waits for the first one to finish. If the initializer throws, the variable is not initialized, and the next pass through the declaration tries again.

```cpp
int attempts = 0;
int init() { if (++attempts < 3) throw attempts; return attempts; }
int get() { static int v = init(); return v; }   // third call succeeds, then no more calls
```

Re-entering the declaration recursively while it is being initialized is undefined behavior, and in practice usually deadlocks or throws. A block-scope static that is constant-initialized never runs an initializer at all.

## Five ways to end a program

| Path | Automatic objects in the current thread | `atexit` handlers and static destructors | `at_quick_exit` handlers | C streams flushed |
| --- | --- | --- | --- | --- |
| `return` from `main` | destroyed (`main`'s own) | yes, interleaved in reverse | no | yes |
| `std::exit(status)` | not destroyed | yes, interleaved in reverse | no | yes |
| `std::quick_exit(status)` | not destroyed | no | yes, in reverse | implementation-defined |
| `std::abort()` | not destroyed | no | no | implementation-defined |
| `std::terminate()` | depends on why it was called | no, with the default handler | no | implementation-defined |

`std::exit` destroys the calling thread's thread-local objects, then runs static destructors and `atexit` handlers, then flushes and closes C streams, removes files made by `std::tmpfile`, and returns the status. Status 0 or `EXIT_SUCCESS` means success, `EXIT_FAILURE` means failure, and any other value has implementation-defined meaning.

```cpp
#include <cstdio>
#include <cstdlib>

struct T { const char* n; ~T() { std::printf("~%s\n", n); } };
T g{"global"};

int main() {
  T l{"local"};
  std::exit(0);     // prints ~global only: l is never destroyed
}
```

`std::quick_exit` (C++11) runs only the `at_quick_exit` handlers, in reverse order of registration, and then calls `std::_Exit`. No objects are destroyed. It exists for programs whose static destructors might race with or deadlock against still-running threads. `std::abort` ends the program abnormally, by way of `SIGABRT`, and runs nothing at all: neither destructors nor handlers.

`std::terminate` calls the current terminate handler, which by default calls `std::abort`. The runtime calls it when an exception escapes `main` or a thread's initial function, escapes a `noexcept` function, escapes a static initializer, a static destructor or an `atexit` handler, or escapes a destructor during stack unwinding. When no handler is found, [except.handle] makes it implementation-defined whether the stack is unwound first; GCC does not unwind, so destructors of `main`'s locals do not run. A terminate handler must not return.

> **Standardese.** [basic.start.term] says the call to `std::exit` is sequenced before the destructions and registered functions it causes, and that destroying statics and calling `atexit` functions are parts of that call. Returning from `main` is defined in [basic.start.main] as leaving `main` and then calling `std::exit` with the returned value.

## Destruction order and `atexit`

Static objects are destroyed in the reverse order in which their constructors, or their dynamic initializations, completed. A statically initialized object is destroyed as if it had been dynamically initialized in its place.

`atexit` handlers are not a separate stack run before or after the destructors. [basic.start.term] places each registration into the same sequence: if an object finishes initialization before a handler is registered, the handler runs before the object is destroyed, and if the registration comes first, the object is destroyed first.

```cpp
#include <cstdio>
#include <cstdlib>

struct T {
  const char* n;
  T(const char* s) : n(s) { std::printf("+%s ", n); }
  ~T() { std::printf("~%s ", n); }
};

void handler() { std::printf("handler "); }

T a("a");
int reg = (std::atexit(handler), 0);
T b("b");

int main() { std::printf("main "); }   // +a +b main ~b handler ~a
```

Two more teardown hazards are worth knowing. A function that contains a static local which has already been destroyed is still callable during later static destruction, but passing through that local's declaration is undefined behavior. And a detached thread that touches a destroyed static object, or uses most of the standard library, during or after static destruction has undefined behavior; this is the hazard `quick_exit` sidesteps.

## What to remember

- `main` must return `int`, may not be used, inlined, made static or constexpr, and falls off the end as `return 0;`.
- Returning from `main` destroys its locals and then calls `std::exit`; calling `std::exit` directly skips the locals.
- Zero and constant initialization happen before all dynamic initialization, so constant-initialized variables are safe everywhere; `constinit` enforces it.
- An implementation may perform dynamic initialization statically, which can change what an early reader sees.
- Dynamic initialization is ordered within a file, partially ordered for inline variables, unordered for template statics, and unordered across files.
- Static locals initialize on first pass, thread-safely, and retry after an exception.
- Static destructors and `atexit` handlers run as one reverse sequence of everything that completed.
- `quick_exit` runs only `at_quick_exit` handlers; `abort` runs nothing; `terminate` calls a handler that defaults to `abort`.
- Whether the stack unwinds before `terminate` for an uncaught exception is implementation-defined.

## Concept Map Outline

- **Startup and termination:** Static initialization, then dynamic initialization, then main, then a reverse teardown chosen by the exit path.
  - **main:** The program's entry point, with rules no other function has.
    - **Declared int:** Return type must be declared int; auto main() -> int is fine, deduction is not.
    - **Forbidden forms:** No inline, static, constexpr, consteval, deleted or coroutine main; it may not be used.
    - **Implicit return 0:** Falling off the end of main is equivalent to return 0.
    - **Return calls exit:** Returning destroys main's locals, then calls std::exit with the value.
  - **Static initialization:** Zero and constant initialization, complete before any dynamic initialization.
    - **Constant init:** Used when the initialization is a constant expression; safe to read from anywhere.
    - **Zero init:** Everything else with static storage is zeroed first.
    - **constinit (C++20):** Requires constant initialization without making the variable const.
    - **Static instead of dynamic:** An implementation may do dynamic init statically, so early readers may see either value.
  - **Dynamic initialization:** Runs code; order depends on the kind of variable.
    - **Ordered:** Ordinary namespace-scope variables follow definition order within one file.
    - **Partially ordered:** Non-template inline variables keep the order they have in every defining file.
    - **Unordered:** Static members of class templates and variable template specializations have no order.
    - **Deferral:** May be deferred until first odr-use of something in the same file; implementation-defined.
    - **Block statics:** Initialized on first pass, thread-safe since C++11, retried if the initializer throws.
  - **Exit paths:** Each way out runs a different subset of the teardown.
    - **std::exit:** Thread-locals, then statics and atexit handlers in one reverse sequence, then C streams.
    - **std::quick_exit:** Only at_quick_exit handlers, in reverse, then _Exit; no objects destroyed.
    - **std::abort:** Abnormal termination; no destructors and no handlers of any kind.
    - **std::terminate:** Calls the terminate handler, abort by default; unwinding before it may not happen.
  - **Teardown order:** Reverse of completion, with atexit registrations in the same sequence.
    - **Reverse completion:** The static object constructed last is destroyed first.
    - **atexit interleaving:** A handler registered after an object completed runs before that object is destroyed.
    - **Dead statics:** Passing through a destroyed static local during later teardown is UB.
    - **Exceptions:** An exception from a static initializer, destructor or atexit handler calls terminate.

## Standardese Quiz Questions

### Question 1 [warmup] ([support.start.term], [basic.start.main], [basic.start.term])

What does this program print?

```cpp
#include <cstdio>
#include <cstdlib>

struct T {
  const char* n;
  ~T() { std::printf("~%s\n", n); }
};

T g{"global"};

int main() {
  T l{"local"};
  std::exit(0);
}
```

A. `~local` then `~global`
B. `~global` only
C. Nothing: `std::exit` runs no destructors
D. `~global` then `~local`

**Answer (B):** `~global` only

**Why:** `std::exit` destroys objects with static storage duration, and thread-locals of the calling thread, but it never returns to its caller, so the automatic object `l` is never destroyed. `return 0;` would print `~local` first, because returning from `main` leaves the function, destroying its locals, before calling `std::exit`. The third option describes `std::quick_exit` or `std::abort`.

### Question 2 [warmup] ([basic.start.main])

Which of these definitions of `main` is well-formed in C++23?

A. `auto main() { return 0; }`
B. `static int main() { return 0; }`
C. `auto main() -> int { }`
D. `constexpr int main() { return 0; }`

**Answer (C):** `auto main() -> int { }`

**Why:** `main` must have a declared return type of `int`, and a trailing return type counts as declaring it, so `auto main() -> int` is fine. Falling off the end of `main` is equivalent to `return 0;`, so the empty body is fine too. A deduced return type is not a declared `int`, and `main` may not be `static`, `inline`, `constexpr` or `consteval`; GCC rejects all three of the others.

### Question 3 [warmup] ([stmt.dcl])

What does this program print?

```cpp
#include <cstdio>

int attempts = 0;

int init() {
  if (++attempts < 3) throw attempts;
  return attempts * 10;
}

int get() {
  static int v = init();
  return v;
}

int main() {
  for (int i = 0; i < 5; ++i) {
    try { get(); } catch (int) {}
  }
  std::printf("%d\n", attempts);
}
```

A. `3`
B. `1`
C. `5`
D. Undefined behavior: `v` is used after its initialization failed

**Answer (A):** `3`

**Why:** [stmt.dcl] says that if the initialization of a block-scope static exits by an exception, the variable is not initialized, and initialization is attempted again the next time control enters the declaration. The first two calls throw, the third succeeds and sets `v` to 30, and the last two calls skip the initializer. `1` would be right only if a failed initialization were never retried.

### Question 4 [tricky] ([basic.start.term], [basic.start.dynamic])

What does this program print?

```cpp
#include <cstdio>
#include <cstdlib>

struct T {
  const char* n;
  T(const char* s) : n(s) { std::printf("+%s ", n); }
  ~T() { std::printf("~%s ", n); }
};

void handler() { std::printf("handler "); }

T a("a");
int reg = (std::atexit(handler), 0);
T b("b");

int main() { std::printf("main "); }
```

A. `+a +b main handler ~b ~a`
B. `+a +b main ~b ~a handler`
C. `+a +b main ~b handler ~a`
D. The relative order of `handler` and the destructors is unspecified

**Answer (C):** `+a +b main ~b handler ~a`

**Why:** The three dynamic initializations are ordered by definition in one file: `a` completes, then `handler` is registered, then `b` completes. [basic.start.term] runs destructors and `atexit` functions as one sequence in reverse: what completed after a registration is destroyed before that handler runs, and what completed before it is destroyed after. So `~b`, `handler`, `~a`. Treating `atexit` handlers as a separate stack gives either of the first two answers.

### Question 5 [tricky] ([support.start.term])

When this program calls `std::quick_exit(0)`, which of the following run?

```cpp
#include <cstdio>
#include <cstdlib>

struct T {
  const char* n;
  ~T() { std::printf("~%s\n", n); }
};

T g{"global"};

void on_exit_fn() { std::puts("atexit"); }
void on_quick() { std::puts("at_quick_exit"); std::fflush(stdout); }

int main() {
  T l{"local"};
  std::atexit(on_exit_fn);
  std::at_quick_exit(on_quick);
  std::quick_exit(0);
}
```

A. Only `on_quick`
B. `on_quick`, then `on_exit_fn`
C. `on_quick`, then the destructor of `g`
D. Nothing: `quick_exit` is like `abort`

**Answer (A):** Only `on_quick`

**Why:** `std::quick_exit` calls the functions registered with `at_quick_exit` in reverse order of registration and then calls `std::_Exit`. It destroys no objects and calls no `atexit` handlers, and whether `_Exit` flushes streams is implementation-defined, which is why the handler flushes `stdout` itself. The second and third options mix in parts of `std::exit`.

### Question 6 [tricky] ([basic.start.static], [basic.start.dynamic])

Two files, `a.cpp` and `b.cpp`, are linked into one program. When `main` starts, what is the value of `x`?

```cpp
// file a.cpp
int f();
int x = f();
int main() { return x; }

// file b.cpp
int y = 5;
int f() { return y; }
```

A. Unspecified: 0 or 5, depending on which file is initialized first
B. 0, because `x` is initialized first
C. Undefined behavior: `y` is read before its initialization
D. 5, guaranteed

**Answer (D):** 5, guaranteed

**Why:** `y` is constant-initialized, and [basic.start.static] says all static initialization strongly happens before any dynamic initialization. So `y` already holds 5 when the dynamic initializer of `x` calls `f`, whichever file's dynamic initialization runs first. The unspecified answer would be right if `y` had a dynamic initializer, such as `int y = compute();`.

### Question 7 [standardese] ([basic.start.static])

These are the only definitions in one file. What does the C++23 standard say about the value of `d2` once initialization is complete?

```cpp
inline double fd() { return 1.0; }
extern double d1;
double d2 = d1;
double d1 = fd();
```

A. It is 0.0, because `d2` is initialized before `d1` in the same file
B. It is unspecified whether it is 0.0 or 1.0
C. It is 1.0, because `fd()` can be evaluated at compile time
D. Undefined behavior: `d1` is read before its lifetime begins

**Answer (B):** It is unspecified whether it is 0.0 or 1.0

**Why:** Both variables have dynamic initializers, since `fd` is not `constexpr`. But [basic.start.static] lets an implementation perform a dynamic initialization statically when the result is the same, and doing that for `d1` is allowed. If it does, `d2` sees 1.0; if not, `d2` is initialized first and sees the zero-initialized 0.0. This is the standard's own example; GCC and Clang give 0.0, which is why the first option is tempting. There is no undefined behavior, because a zero-initialized `double` may be read.

### Question 8 [standardese] ([except.handle], [except.terminate])

The exception escapes `main` and no handler exists. Is the destructor of `local` guaranteed to run?

```cpp
#include <cstdio>

struct T { ~T() { std::puts("~T"); } };

int main() {
  T local;
  throw 42;
}
```

A. Yes: the stack is always unwound before `std::terminate` is called
B. No: it is guaranteed not to run, because `std::terminate` is called at the throw
C. Undefined behavior: throwing out of `main` is not allowed
D. It is implementation-defined whether the stack is unwound before `std::terminate` is called

**Answer (D):** It is implementation-defined whether the stack is unwound before `std::terminate` is called

**Why:** When no matching handler is found, [except.handle] says `std::terminate` is called and whether the stack is unwound first is implementation-defined. GCC does not unwind, so `~T` is not printed there, but another implementation may unwind. This is why long-running programs catch everything in `main` when they need destructors to run.

---

# Track: Types and initialization

What a type promises, how values convert, and every spelling of initialization and deduction.

# Fundamental types and arithmetic conversions

> The standard promises minimum widths and an ordering of integer types, not exact sizes, and every arithmetic operator first promotes small operands to int and then pulls both sides to a common type. Most signed and unsigned surprises fall out of those two steps.

- **Source:** C++ Atlas (https://cppatlas.com/topics/fundamental-types-and-arithmetic-conversions)
- **Track:** Types and initialization
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [basic.fundamental] (https://eel.is/c++draft/basic.fundamental), [basic.extended.fp] (https://eel.is/c++draft/basic.extended.fp), [conv.rank] (https://eel.is/c++draft/conv.rank), [conv.prom] (https://eel.is/c++draft/conv.prom), [conv.integral] (https://eel.is/c++draft/conv.integral), [conv.bool] (https://eel.is/c++draft/conv.bool), [expr.arith.conv] (https://eel.is/c++draft/expr.arith.conv), [cstdint.syn] (https://eel.is/c++draft/cstdint.syn), [stdfloat.syn] (https://eel.is/c++draft/stdfloat.syn)
- **cppreference links:** [Fundamental types](https://en.cppreference.com/w/cpp/language/types), [Usual arithmetic conversions](https://en.cppreference.com/w/cpp/language/usual_arithmetic_conversions), [Arithmetic operators](https://en.cppreference.com/w/cpp/language/operator_arithmetic), [Fixed width integer types](https://en.cppreference.com/w/cpp/types/integer), [Fixed width floating-point types](https://en.cppreference.com/w/cpp/types/floating-point), [Safe integer comparison (std::cmp_less and friends)](https://en.cppreference.com/w/cpp/utility/intcmp)
- **Prerequisites:** value-categories

## The one idea

An arithmetic expression in C++ never operates on the types you wrote. Before a binary operator such as `+`, `<` or `*` does anything, two conversions run. First, every operand narrower than `int` is **promoted**, usually to `int`. Then the **usual arithmetic conversions** bring both operands to a single common type, chosen by a fixed ladder of rules. The operation happens in that common type, and the result has that type.

The standard does not tell you how wide most of these types are. It gives minimum widths, an ordering, and since C++20 a fixed representation for signed integers. Everything else, including whether plain `char` is signed, is the implementation's choice.

> **Mental model.** Small types do not exist in arithmetic: they become `int` on the way in. After that, if one side is unsigned and at least as wide as the other, the signed side becomes unsigned, and negative numbers turn into huge positive ones.

## What the standard guarantees about the integer types

There are five standard signed integer types, `signed char`, `short`, `int`, `long` and `long long`, each with an unsigned counterpart of the same size. Since C++20, [basic.fundamental] states minimum widths for them: 8, 16, 16, 32 and 64 bits. Each type in the list has at least the range of the one before it. `sizeof(char)` is 1 by definition, and a byte has at least 8 bits, but it can have more.

That is the whole guarantee. `int` is 32 bits on every mainstream desktop platform, but 16 bits is conforming. `long` is 64 bits on 64-bit Linux and macOS (the LP64 model) and 32 bits on 64-bit Windows (LLP64). Code that assumes `long` holds a pointer is not portable.

C++20 adopted P1236, the wording for P0907: signed integers are **two's complement**. A signed type of width N holds exactly the values from -2^(N-1) to 2^(N-1)-1, and the same bit pattern is shared with the unsigned type for non-negative values. Two consequences follow. Converting an out-of-range value to a signed type is now well-defined and wraps modulo 2^N, where before C++20 the result was implementation-defined. Signed overflow in arithmetic, however, is still undefined behavior; the integer-arithmetic-and-overflow topic covers that side.

```cpp
#include <climits>

static_assert(static_cast<signed char>(200) == -56);  // guaranteed since C++20
static_assert(static_cast<unsigned>(-1) == UINT_MAX); // modular, always was
```

> **Standardese.** [conv.integral] says that converting an integer to an integer type of width N produces the unique value of the destination type that is congruent to the source modulo 2^N. That sentence covers both signed and unsigned destinations from C++20 on.

## char is three types

`char`, `signed char` and `unsigned char` are three distinct types, even though `char` has the same representation and range as one of the other two. Which one is implementation-defined. On x86-64 Linux and on Apple's arm64 platforms, plain `char` is signed; on arm64 Linux it is unsigned. GCC and Clang let you flip it with `-funsigned-char`, which is a fine way to find code that depends on it.

```cpp
#include <type_traits>

static_assert(!std::is_same_v<char, signed char>);    // always distinct
static_assert(!std::is_same_v<char, unsigned char>);  // also distinct

bool high_bit(char c) { return c < 0; }  // true for '\xff' only if char is signed
```

The character types `char8_t`, `char16_t`, `char32_t` and `wchar_t` are distinct types too, each with an integer type as its underlying type. Their encoding questions belong to the character-types-and-unicode topic; here they matter only for how they promote.

## Integral promotion

[conv.prom] turns every narrow integer operand into something at least as wide as `int` before arithmetic. The rules are:

- An integer type whose conversion rank is below `int`'s, other than `bool` and the character types listed below, becomes `int` if `int` can hold all its values, otherwise `unsigned int`. This covers `char`, `signed char`, `unsigned char`, `short` and `unsigned short`.
- `bool` becomes `int`, with `false` as 0 and `true` as 1.
- `wchar_t`, `char8_t`, `char16_t` and `char32_t` become the first of `int`, `unsigned int`, `long`, `unsigned long`, `long long` and `unsigned long long` that can hold every value of their underlying type. With a 32-bit `int`, `char32_t` therefore promotes to `unsigned int`.
- An unscoped enumeration without a fixed underlying type promotes along the same list, starting from `int`; one with a fixed underlying type promotes to that type, and then onward.
- A bit-field promotes to `int` if `int` can hold all its values, otherwise `unsigned int` if that can.

```cpp
#include <cstdint>
#include <type_traits>

std::uint8_t a = 200, b = 200;
auto s = a + b;                 // int, value 400: no wraparound at 8 bits
static_assert(std::is_same_v<decltype(s), int>);
static_assert(std::is_same_v<decltype('a' + 'b'), int>);
static_assert(std::is_same_v<decltype(true + true), int>);  // value 2
```

Promotion is why `unsigned short` arithmetic can be undefined. If `int` is 32 bits, both operands of `x * y` become signed `int`, and 65535 times 65535 overflows a signed type.

> **Pitfall.** Multiplying two `unsigned short` or `std::uint16_t` values that are near the top of their range overflows signed `int` on a typical platform. The unsigned operand types do not protect you, because the multiplication happens after promotion. Cast one operand to `unsigned` first, or use `std::uint32_t` from the start.

## Conversion rank and the usual arithmetic conversions

Every integer type has an **integer conversion rank** ([conv.rank]). `long long` outranks `long`, which outranks `int`, then `short`, then `signed char`. An unsigned type has the rank of its signed counterpart. `char`, `signed char` and `unsigned char` share a rank. `bool` ranks lowest of all. The character types have the rank of their underlying types, and an extended integer type ranks below a standard type of the same width.

[expr.arith.conv] then applies these steps in order, for operators such as `+`, `-`, `*`, `/`, `%`, the comparisons, the bitwise operators and the second and third operands of `?:`:

1. If either operand has scoped enumeration type, no conversion is done, and the operands must have the same type.
2. If either operand is floating, an integer operand converts to the floating type; of two floating types, the one of lesser floating-point conversion rank converts to the other, and unordered ranks make the expression ill-formed.
3. Otherwise both operands are promoted, and if the types now match, that is the result.
4. If both are signed or both unsigned, the one of lesser rank converts to the other.
5. If the unsigned operand has rank greater than or equal to the signed one, the signed operand converts to the unsigned type.
6. Otherwise, if the signed type can represent every value of the unsigned type, the unsigned operand converts to the signed type.
7. Otherwise both convert to the unsigned counterpart of the signed type.

Steps 6 and 7 are where the platform leaks in. With LP64, `long` is wider than `unsigned int`, so step 6 applies and `-1L < 1u` is true. On LLP64, `long` and `unsigned int` are both 32 bits, step 7 applies, and the same comparison is false.

```cpp
#include <type_traits>

static_assert(!(-1 < 0u));  // step 5: -1 becomes UINT_MAX
static_assert(std::is_same_v<decltype(1u + 1ll), long long>);  // step 6 wherever long long
                                                               // is wider than unsigned int
// On LP64, long and unsigned long are both 64 bits:
//   1ul + 1ll has type unsigned long long (step 7)
```

Mixing an unscoped enumeration with a floating type, or two different enumeration types, was deprecated in C++20 and is ill-formed in C++26.

## Signed and unsigned comparison traps

Step 5 means any comparison between a negative `int` and an `unsigned int` or `std::size_t` is wrong. Compilers warn under `-Wsign-compare`, which `-Wall` enables in C++ for GCC. The common shapes are a container's `size()` compared with a signed index, `v.size() - 1` on an empty vector wrapping to the maximum value, and a countdown loop over an unsigned index whose condition `i >= 0` is always true.

```cpp
#include <utility>
#include <vector>

bool safe(int i, const std::vector<int>& v) {
  // return i < v.size();          // i == -1 converts to a huge value: false
  return std::cmp_less(i, v.size());  // C++20: compares mathematical values
}
```

C++20 added `std::cmp_equal`, `std::cmp_less` and the rest of the family in `<utility>`, which compare the mathematical values of any two standard integer types, and `std::ssize`, which returns a signed size.

## bool, fixed-width types and extended floating types

**bool.** A boolean conversion ([conv.bool]) turns a zero value, a null pointer or a null member pointer into `false` and anything else into `true`; `bool b = 0.5;` is `true`. Going the other way, `bool` promotes to `int`. Incrementing a `bool` was removed in C++17, and decrementing it was never allowed.

**Fixed-width integers.** `<cstdint>` provides `std::int8_t` through `std::int64_t` and their unsigned counterparts. They are optional: they exist only if the implementation has a type of exactly that width with no padding bits. `std::int_leastN_t` and `std::int_fastN_t` for 8, 16, 32 and 64 are always present. `std::uint8_t` is almost always an alias for `unsigned char`, so it promotes to `int` and streams as a character.

**Floating types.** `float`, `double` and `long double` only promise that each has at least the precision of the one before; IEEE 754 is what implementations do, and `std::numeric_limits<T>::is_iec559` reports it. C++23 (P1467) added optional **extended floating-point types** in `<stdfloat>`: `std::float16_t`, `std::float32_t`, `std::float64_t`, `std::float128_t` and `std::bfloat16_t`, with literal suffixes such as `f16` and `bf16`. They are distinct from the standard types even when the format matches, and P1467 gave every floating type a **floating-point conversion rank**. A conversion from a higher rank to a lower one is no longer implicit when an extended type is involved.

```cpp
#include <stdfloat>
#include <type_traits>

std::float16_t h = 1.0f16;    // OK
// std::float16_t g = 1.0;    // ill-formed: double has greater rank
static_assert(std::is_same_v<decltype(1.0f + 1.0f32), std::float32_t>);
// same rank as float, but the extended type has the greater subrank
```

Precision, rounding and special values are the floating-point-and-numerics topic's subject.

## What to remember

- The standard fixes minimum widths (8, 16, 16, 32, 64 bits) and an ordering, not sizes; LP64 and LLP64 disagree about `long`.
- Since C++20 signed integers are two's complement and narrowing integer conversions wrap modulo 2^N; signed arithmetic overflow is still undefined.
- `char`, `signed char` and `unsigned char` are distinct; `char`'s signedness is implementation-defined.
- Operands narrower than `int`, including `bool`, `char` and `unsigned short`, are promoted to `int` before arithmetic.
- In mixed comparisons, an unsigned operand of equal or higher rank wins, so `-1 < 0u` is false; use `std::cmp_less` and `std::ssize`.
- Whether a signed type absorbs an unsigned one depends on the platform's widths.
- Exact-width `std::intN_t` types are optional; the `least` and `fast` variants are not.
- C++23 extended floating types have their own conversion ranks and do not accept implicit narrowing from `double`.

## Concept Map Outline

- **Fundamental types:** Minimum widths and an ordering, then promotion and the usual arithmetic conversions before every operator.
  - **Integer guarantees:** The standard fixes minimum widths and a range ordering, not exact sizes.
    - **Minimum widths:** signed char, short, int, long, long long: at least 8, 16, 16, 32 and 64 bits.
    - **LP64 vs LLP64:** long is 64 bits on Linux and macOS but 32 bits on 64-bit Windows.
    - **Two's complement (C++20):** Signed range is exactly -2^(N-1) to 2^(N-1)-1; integer conversions wrap modulo 2^N.
    - **Overflow still UB:** Signed arithmetic that leaves the type's range is undefined even in C++20.
  - **char:** char, signed char and unsigned char are three distinct types.
    - **Signedness:** Implementation-defined: signed on x86-64 Linux and Apple arm64, unsigned on arm64 Linux.
    - **Character types:** char8_t, char16_t, char32_t and wchar_t are distinct types with underlying integer types.
  - **Integral promotion:** Operands narrower than int are widened before arithmetic.
    - **Small to int:** char, short and their variants become int if int holds all values, else unsigned int.
    - **bool to int:** false becomes 0 and true becomes 1, so true + true is the int 2.
    - **Wide characters:** Promote to the first of int, unsigned, long and so on that fits; char32_t usually becomes unsigned.
    - **unsigned short trap:** Two large unsigned shorts multiply as signed int and can overflow: undefined behavior.
  - **Usual conversions:** [expr.arith.conv] brings both operands of a binary operator to one common type.
    - **Conversion rank:** long long > long > int > short > signed char; unsigned matches signed; bool is lowest.
    - **Floating wins:** An integer operand converts to the floating type; between floats, the lower rank converts.
    - **Unsigned wins ties:** If the unsigned type's rank is at least the signed one's, the signed operand becomes unsigned.
    - **Platform-dependent case:** A wider signed type absorbs the unsigned one only if it can represent all of its values.
    - **Enum mixing:** Enum with float, or two enum types, was deprecated in C++20 and is ill-formed in C++26.
  - **Comparison traps:** Mixed-sign comparisons convert negatives into huge unsigned values.
    - **-1 < 0u is false:** Same rank, so -1 converts to UINT_MAX before comparing.
    - **size() - 1:** On an empty container the subtraction wraps to the maximum size_t value.
    - **std::cmp_less (C++20):** Compares the mathematical values of any two standard integer types.
  - **Other types:** bool, fixed-width integers and the floating types.
    - **bool conversion:** Zero, null pointer and null member pointer become false; everything else true.
    - **Fixed-width integers:** std::intN_t is optional; std::int_leastN_t and std::int_fastN_t always exist.
    - **Extended floats (C++23):** std::float16_t and friends in <stdfloat>; implicit conversion to a lower rank is not allowed.

## Standardese Quiz Questions

### Question 1 [warmup] ([conv.prom], [expr.arith.conv])

On a platform with 8-bit `char` and 32-bit `int`, what is the type of `x`?

```cpp
char a = 'a', b = 'b';
auto x = a + b;
```

A. `char`
B. `int`
C. Implementation-defined: `int` if `char` is signed, `unsigned int` otherwise
D. `unsigned char`

**Answer (B):** `int`

**Why:** Both operands are promoted before the addition. `char` has a conversion rank below `int`, and a 32-bit `int` can represent every value of an 8-bit `char`, signed or unsigned, so both operands become `int` and so does the result. Signedness would only matter on an exotic platform where `char` is as wide as `int`; there an unsigned `char` would promote to `unsigned int`. Arithmetic never happens in `char`, so the first option is never right.

### Question 2 [warmup] ([expr.arith.conv], [conv.integral], [expr.rel])

What does this program print?

```cpp
#include <cstdio>

int main() {
  std::printf("%d\n", -1 < 0u);
}
```

A. `1`
B. Undefined behavior: signed and unsigned comparison
C. `0`
D. Implementation-defined

**Answer (C):** `0`

**Why:** The operands are `int` and `unsigned int`, which have the same conversion rank, so the usual arithmetic conversions turn the signed operand into `unsigned int`. `-1` becomes `UINT_MAX`, which is not less than `0u`, so the comparison is `false` and prints `0`. Nothing here is undefined; the conversion to unsigned is modular and fully specified, which is exactly why the bug is silent.

### Question 3 [warmup] ([conv.integral], [basic.fundamental])

In C++20 or later, with `CHAR_BIT == 8`, what does this program print?

```cpp
#include <cstdio>

int main() {
  signed char c = static_cast<signed char>(200);
  std::printf("%d\n", c);
}
```

A. `-56`
B. Implementation-defined
C. Undefined behavior: 200 does not fit in `signed char`
D. `127`

**Answer (A):** `-56`

**Why:** Since C++20, an integer conversion to a type of width N yields the unique value congruent to the source modulo 2^N, and signed types are two's complement. 200 minus 256 is -56. Before C++20 the result of converting an out-of-range value to a signed type was implementation-defined, which is the tempting answer; it was never undefined, and no conversion saturates.

### Question 4 [tricky] ([conv.prom], [expr.pre], [expr.mul])

Assume `int` is 32 bits and `unsigned short` is 16 bits. What does the standard say about this program?

```cpp
#include <cstdio>

int main() {
  unsigned short a = 65535, b = 65535;
  unsigned long long r = a * b;
  std::printf("%llu\n", r);
}
```

A. It prints `4294836225`
B. It prints `1`, the product reduced modulo 2^16
C. The result is implementation-defined
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** Both operands are promoted to `int`, because `int` can represent every `unsigned short` value. The multiplication is therefore signed `int` arithmetic, and 4294836225 exceeds `INT_MAX`, which is signed overflow and undefined behavior. The tempting `4294836225` assumes the product is computed in a wide unsigned type; an unoptimized GCC build on arm64 actually wraps to -131071 and then prints `18446744073709420545`, and in a constant expression both GCC and Clang reject it. Writing `1u * a * b` makes the arithmetic unsigned.

### Question 5 [tricky] ([basic.fundamental], [lex.ccon])

With `CHAR_BIT == 8` and C++20 or later, what does this program print?

```cpp
#include <cstdio>

int main() {
  char c = '\xff';
  std::puts(c < 0 ? "negative" : "non-negative");
}
```

A. `negative`
B. Implementation-defined: it depends on whether `char` is signed
C. `non-negative`
D. Undefined behavior

**Answer (B):** Implementation-defined: it depends on whether `char` is signed

**Why:** Plain `char` has the same range as either `signed char` or `unsigned char`, and which one is implementation-defined. Where `char` is signed, as on x86-64 Linux and Apple arm64, `'\xff'` holds -1 and the program prints `negative`; where it is unsigned, as on arm64 Linux, it holds 255. Either way the value is well-defined, so there is no undefined behavior.

### Question 6 [tricky] ([expr.arith.conv], [conv.rank])

On an LP64 platform (32-bit `int`, 64-bit `long`), what does this program print?

```cpp
#include <cstdio>

int main() {
  std::printf("%d\n", -1L < 1u);
}
```

A. `0`, because the signed operand converts to unsigned
B. Implementation-defined
C. `1`
D. Undefined behavior

**Answer (C):** `1`

**Why:** `long` has a higher rank than `unsigned int`, and on LP64 it can represent every `unsigned int` value, so the unsigned operand converts to `long` and the comparison is the honest -1 < 1. The tempting `0` is what happens on 64-bit Windows (LLP64): there `long` is 32 bits, cannot hold all `unsigned int` values, and both operands become `unsigned long`.

### Question 7 [standardese] ([expr.arith.conv], [conv.rank])

On an LP64 platform, where `long` and `long long` are both 64 bits, what is the type of `1ul + 1ll`?

A. `unsigned long long`
B. `long long`
C. `unsigned long`
D. Ill-formed: neither type can represent the other

**Answer (A):** `unsigned long long`

**Why:** `long long` has the greater rank, so the rule that converts the signed operand to the unsigned type does not apply. The next rule asks whether `long long` can represent every `unsigned long` value; with both 64 bits it cannot. The final rule then converts both operands to the unsigned counterpart of the signed type, `unsigned long long`. `long long` is the tempting answer because it has the higher rank, but rank alone does not decide it.

### Question 8 [standardese] ([conv.rank], [expr.arith.conv], [basic.extended.fp])

In C++23, on an implementation that provides `std::float32_t` with the same format as `float`, what is the type of `1.0f + 1.0f32`?

```cpp
#include <stdfloat>

auto x = 1.0f + 1.0f32;
```

A. `float`
B. `double`
C. Ill-formed: the two types have unordered conversion ranks
D. `std::float32_t`

**Answer (D):** `std::float32_t`

**Why:** P1467 gives `float` and `std::float32_t` equal floating-point conversion rank when they share a format, and gives the extended type the greater conversion subrank. The usual arithmetic conversions convert the operand of lesser rank, or of equal rank and lesser subrank, to the other type, so the result is `std::float32_t`. Ranks are unordered only between types whose value sets do not nest, such as `std::float16_t` and `std::bfloat16_t`.

# Implicit conversions

> An implicit conversion is a short, fixed pipeline of standard conversions, optionally wrapped around exactly one user-defined conversion. Knowing the slots in that pipeline explains why some conversions happen silently, why narrowing is banned only in braces, and why a second user-defined step is never taken.

- **Source:** C++ Atlas (https://cppatlas.com/topics/implicit-conversions)
- **Track:** Types and initialization
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [conv.general] (https://eel.is/c++draft/conv.general), [conv.lval] (https://eel.is/c++draft/conv.lval), [conv.array] (https://eel.is/c++draft/conv.array), [conv.func] (https://eel.is/c++draft/conv.func), [conv.qual] (https://eel.is/c++draft/conv.qual), [conv.prom] (https://eel.is/c++draft/conv.prom), [conv.fpint] (https://eel.is/c++draft/conv.fpint), [conv.ptr] (https://eel.is/c++draft/conv.ptr), [conv.fctptr] (https://eel.is/c++draft/conv.fctptr), [conv.bool] (https://eel.is/c++draft/conv.bool), [dcl.init.list] (https://eel.is/c++draft/dcl.init.list), [expr.const] (https://eel.is/c++draft/expr.const), [class.conv] (https://eel.is/c++draft/class.conv), [over.best.ics] (https://eel.is/c++draft/over.best.ics)
- **cppreference links:** [Implicit conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion), [List-initialization (narrowing conversions)](https://en.cppreference.com/w/cpp/language/list_initialization), [Copy-initialization](https://en.cppreference.com/w/cpp/language/copy_initialization), [nullptr, the pointer literal](https://en.cppreference.com/w/cpp/language/nullptr), [Overload resolution](https://en.cppreference.com/w/cpp/language/overload_resolution)
- **Prerequisites:** value-categories, fundamental-types-and-arithmetic-conversions

## The one idea

Whenever an expression of one type is used where another type is needed, such as an argument, an initializer, a return value or an operand, the compiler looks for an **implicit conversion sequence**. That sequence is not open-ended. It is either a **standard conversion sequence**, a fixed pipeline with at most one step in each of four slots, or a **user-defined conversion sequence**: a standard sequence, then one constructor or conversion function, then another standard sequence.

Everything else follows from that shape. A conversion that needs two steps in the same slot does not happen. A conversion that needs two user-defined steps does not happen. And overload resolution ranks candidate functions by comparing these sequences slot by slot, which is the overload-resolution topic's subject.

> **Mental model.** Picture four optional boxes in a row: fix the value category, change the type, drop `noexcept`, add `const`. A standard conversion passes through each box at most once. A user-defined conversion is one extra box in the middle, and there is only ever one.

## The four slots of a standard conversion sequence

[conv.general] lists the order:

1. At most one of **lvalue-to-rvalue**, **array-to-pointer** or **function-to-pointer** conversion.
2. At most one of the **promotions**, the integral, floating and floating-integral **conversions**, the **pointer** and **pointer-to-member** conversions, or the **boolean** conversion.
3. At most one **function pointer conversion**, which drops `noexcept` (C++17).
4. At most one **qualification conversion**, which adds cv-qualifiers below the top level.

The first slot fixes the value category and the shape. Lvalue-to-rvalue conversion reads the value out of a glvalue of a non-array, non-function type; it is what happens when you use a variable's value. Array-to-pointer turns an array into a pointer to its first element, and function-to-pointer turns a function into a pointer to it.

```cpp
int a[3];
int* p = a;              // array-to-pointer
int (*pa)[3] = &a;       // no conversion: &a already has type int(*)[3]
void g();
void (*fp)() = g;        // function-to-pointer
const int* cp = p;       // qualification conversion only
const void* vp = a;      // array-to-pointer, pointer conversion, qualification
```

A prvalue of class type does not go through these slots; temporary materialization is a separate standard conversion that turns a prvalue into an xvalue when a reference binds to it or a member is accessed, as the value-categories topic explains.

## Promotions, conversions and the boolean conversion

The second slot distinguishes **promotions** from **conversions**, and the difference matters even though both change the type. Integral promotion widens a narrow integer to `int` or `unsigned int`, and floating-point promotion turns `float` into `double`. Nothing else is a promotion: `int` to `long`, `short` to `long` and `float` to `long double` are conversions. Overload resolution ranks a promotion better than a conversion, so a `short` argument picks `f(int)` over `f(double)`, but finds `f(long)` and `f(double)` equally good.

```cpp
void f(long);
void f(double);

void test(short s, float x) {
  f(x);     // OK: float to double is a promotion, beats float to long
  // f(s);  // ill-formed: short to long and short to double are both conversions
}
```

The conversions themselves have value rules. A floating value converted to an integer is truncated toward zero, and if the truncated value does not fit, the behavior is undefined. An integer converted to a floating type is exact when possible, otherwise one of the two nearest values chosen in an implementation-defined way, and undefined if it is out of range. Integer to integer conversion is modular, as the fundamental-types-and-arithmetic-conversions topic describes.

The **boolean conversion** turns an arithmetic, unscoped enumeration, pointer or pointer-to-member value into `bool`: zero and null become `false`, everything else `true`. It sits in the same slot as the other conversions, so it is always a conversion, never a promotion, and it is a standard conversion, which makes it beat any user-defined conversion.

```cpp
#include <cstdio>
#include <string>

void f(bool)        { std::puts("bool"); }
void f(std::string) { std::puts("string"); }

int main() { f("hello"); }  // prints bool
```

> **Pitfall.** A string literal is an array, so it decays to `const char*`, and a pointer converts to `bool` with a standard conversion sequence. Constructing `std::string` is a user-defined conversion, which always ranks worse. An overload taking `bool` silently captures every string literal argument.

## Pointer conversions and null pointer constants

The pointer conversions in the second slot are:

- A **null pointer constant** converts to any pointer or pointer-to-member type, giving a null value.
- A pointer to a cv-qualified object type converts to a pointer to `void` with the same or more cv-qualification (the qualification part being slot 4). The reverse is not implicit in C++, unlike C.
- A pointer to a derived class converts to a pointer to a base class, provided the base is accessible and unambiguous. A null pointer stays null; otherwise the result points to the base subobject, which may be at a different address.

[conv.ptr] defines a null pointer constant as an **integer literal** with value zero or a prvalue of type `std::nullptr_t`. Since C++11, through CWG 903, an arbitrary integral constant expression that evaluates to zero no longer qualifies, so `1 - 1`, a `const int` holding zero, `false` and `'\0'` are not null pointer constants. `0L` and `0x0` still are, because they are integer literals.

```cpp
int* a = 0;              // OK: integer literal
int* b = 0L;             // OK: integer literal of type long
int* c = nullptr;        // OK: std::nullptr_t
// int* d = 1 - 1;       // ill-formed since C++11
// int* e = false;       // ill-formed since C++11: a boolean literal
// const int z = 0;
// int* f = z;           // ill-formed since C++11, valid in C++03
```

Slot 3, the function pointer conversion, lets a pointer to a `noexcept` function convert to a pointer to a potentially-throwing function of the same type, and the same for pointers to member functions. The reverse would let a throwing function hide behind a `noexcept` type, so it is not allowed. Slot 4, the qualification conversion, adds `const` and `volatile` at levels below the top; the rules for multi-level pointers, including why `int**` does not convert to `const int**`, belong to the const-volatile-and-qualifiers topic.

## Narrowing: banned in braces and constant expressions

A **narrowing conversion** ([dcl.init.list]) is an implicit conversion that may lose information:

- floating to integer;
- floating to a floating type of lower conversion rank, unless the source is a constant expression whose value is within the destination's range, even if not exactly representable;
- integer or unscoped enumeration to a floating type, unless the source is a constant expression whose value is exactly representable;
- integer or unscoped enumeration to an integer type that cannot represent all its values, unless the source is a constant expression whose value fits;
- pointer or pointer-to-member to `bool`, added in C++20 by P1957 and applied as a defect report.

Narrowing is still a valid implicit conversion. It is banned only in particular contexts: list-initialization in all its forms, including `T{x}`, `return {x};` and aggregate member initializers in braces, and **converted constant expressions**, which are used for non-type template arguments, `case` labels, array bounds, enumerator values with a fixed underlying type, `noexcept(...)` and `explicit(...)`. C++20 parenthesized aggregate initialization deliberately allows narrowing.

```cpp
struct A { int x; };

void demo(double d, int i, int* p) {
  int a = d;           // OK: truncates
  // int b{d};         // ill-formed: floating to integer
  constexpr int k = 10;
  char c{k};           // OK: constant whose value fits
  // char e{i};        // ill-formed: i is not a constant expression
  // bool f{p};        // ill-formed since C++20 (P1957)
  A g(3.5);            // OK in C++20: parentheses allow narrowing
  (void)a; (void)c; (void)g;
}

template <bool B> struct Flag {};
// Flag<2> bad;        // ill-formed: narrowing in a converted constant expression
```

GCC reports a non-constant narrowing in braces only as a warning by default, which `-Werror=narrowing` or `-pedantic-errors` turns into an error. The program is ill-formed regardless; Clang rejects it outright.

> **Standardese.** [expr.const] defines a converted constant expression of type T as an expression implicitly converted to T where the conversion sequence contains only certain conversions and, for integral and floating sources, no narrowing. That one sentence is why `Flag<2>` and `void f() noexcept(2);` are errors.

## Contextual conversion to bool

Some language constructs need a truth value and use a stronger rule than implicit conversion. An expression is **contextually converted to bool** when it is the condition of `if`, `while`, `for` or `do`, an operand of `!`, `&&` or `||`, the first operand of `?:`, or the operand of `static_assert`, `if constexpr`, `noexcept(...)` or `explicit(...)`. Contextual conversion means the expression is used as if to direct-initialize a `bool`, so **explicit conversion functions are considered**. That is what makes `explicit operator bool` usable in conditions but not in assignments; the conversion-functions-and-explicit topic covers writing one.

```cpp
struct Handle {
  explicit operator bool() const { return true; }
};

void use(Handle h) {
  if (h) {}              // OK: contextual
  bool ok = !h || h;     // OK: both operands are contextual
  // bool b = h;         // ill-formed: copy-initialization ignores explicit
  (void)ok;
}
```

C++23 adopted P1401, which allows narrowing in the contextual conversions of `static_assert` and `if constexpr`, so `static_assert(2);` is valid; GCC and Clang accept it in C++20 mode as well. `noexcept(...)` and `explicit(...)` still reject narrowing. A requires-clause is different again: an atomic constraint is not converted at all and must have type `bool` exactly, so `requires (sizeof(T))` is ill-formed.

## At most one user-defined conversion

A **user-defined conversion** is a call to a converting constructor or a conversion function. [class.conv] says at most one is applied implicitly to a single value. A user-defined conversion sequence therefore looks like this:

```text
  source --[standard seq 1]--> ctor param / object --[ONE user-defined]--> --[standard seq 2]--> target
```

The standard sequences on either side can do the usual work, such as decaying an array before a constructor taking `const char*`, or turning a conversion function's `int` result into a `double`. What cannot happen is a chain of two user-defined steps, such as `const char*` to `std::string` and then `std::string` to a class with a constructor from `std::string`.

```cpp
#include <string>

struct Name {
  Name(std::string) {}
};

// Name n1 = "Ada";    // ill-formed: const char* -> std::string -> Name is two steps
Name n2("Ada");        // OK: the constructor is called directly; its argument needs one
Name n3 = {"Ada"};     // OK: list-initialization also calls the constructor directly
// void take(Name);
// take("Ada");        // ill-formed: same two-step chain as n1
```

Direct-initialization and list-initialization succeed because they pick `Name`'s constructor by overload resolution, so the only implicit conversion left is from the argument to the parameter type, which needs one user-defined step. Copy-initialization from a different type has to find a single conversion all the way to `Name`.

Derived-to-base conversions do not count toward this limit. Binding a `const Base&` to a `Derived`, or converting `Derived*` to `Base*`, is a standard conversion, and a conversion function returning `Derived` can be followed by a derived-to-base step to reach `Base`.

## What to remember

- A standard conversion sequence has four ordered slots: value transformation, promotion or conversion, function pointer conversion, qualification conversion.
- Only narrow integers to `int` and `float` to `double` are promotions; promotions outrank conversions in overload resolution.
- Pointer to `bool` is a standard conversion and beats any constructor, which is why `f("text")` can pick `f(bool)`.
- A null pointer constant is an integer literal zero or a `std::nullptr_t` prvalue; `false`, `'\0'` and `const int z = 0` are not, since C++11.
- Derived-to-base pointer conversion needs an accessible, unambiguous base; `void*` never converts implicitly to `T*`.
- Narrowing is banned in list-initialization and converted constant expressions, including template arguments and `noexcept(...)`; pointer to `bool` became narrowing in C++20.
- Contextual conversion to bool considers explicit conversion functions; requires-clauses need exactly `bool`.
- At most one user-defined conversion per implicit conversion; `Name n = "Ada";` fails where `Name n("Ada");` works.

## Concept Map Outline

- **Implicit conversions:** A fixed pipeline of standard conversions, optionally around exactly one user-defined conversion.
  - **Standard sequence slots:** At most one conversion from each of four ordered slots.
    - **Value transformation:** Lvalue-to-rvalue, array-to-pointer or function-to-pointer, at most one.
    - **Type change:** One promotion, arithmetic, pointer, pointer-to-member or boolean conversion.
    - **Function pointer (C++17):** A pointer to a noexcept function converts to a pointer to a throwing one, not back.
    - **Qualification:** Adds const or volatile below the top level, last in the sequence.
  - **Promotion vs conversion:** Both change the type, but promotions rank better in overload resolution.
    - **Promotions:** Only narrow integers to int or unsigned int, and float to double.
    - **short to long:** A conversion, so f(long) and f(double) are ambiguous for a short.
    - **Floating to integer:** Truncates toward zero; undefined if the result does not fit.
    - **Boolean conversion:** Zero and null become false; it beats any user-defined conversion.
  - **Pointer conversions:** Null pointer constants, void pointers and derived-to-base.
    - **Null pointer constant:** Integer literal zero or a std::nullptr_t prvalue; false and const int zero are not (C++11).
    - **To void*:** Any object pointer converts to cv void*; void* never converts back implicitly.
    - **Derived to base:** Needs an accessible, unambiguous base; the address may change; null stays null.
  - **Narrowing:** A lossy implicit conversion that is banned only in certain contexts.
    - **What narrows:** Float to int, wide to narrow, int to float, and pointer to bool since C++20.
    - **Constant exception:** A constant expression whose value fits is not narrowing, except float to int.
    - **Banned in braces:** Every form of list-initialization rejects narrowing; C++20 parenthesized aggregates allow it.
    - **Converted constants:** Template arguments, case labels, array bounds and noexcept(...) reject narrowing.
  - **Contextual bool:** Conditions and logical operators convert as if direct-initializing a bool.
    - **Explicit is allowed:** explicit operator bool works in if, !, && and ?: but not in bool b = x.
    - **P1401 (C++23):** static_assert and if constexpr accept narrowing to bool; noexcept(...) does not.
    - **Requires-clauses:** Atomic constraints are not converted and must have type bool exactly.
  - **User-defined step:** A constructor or conversion function, applied at most once implicitly.
    - **Shape:** Standard sequence, then one user-defined conversion, then another standard sequence.
    - **No chaining:** const char* to std::string to Name is two steps, so Name n = "Ada" fails.
    - **Direct init escapes:** Name n("Ada") calls the constructor, leaving only one conversion for its argument.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.init.list], [conv.fpint])

Which line makes this translation unit ill-formed?

```cpp
int a = 3.9;    // (A)
int b(3.9);     // (B)
int c{3.9};     // (C)
int d = {3};    // (D)
```

A. (A)
B. (B)
C. (C)
D. (D)

**Answer (C):** (C)

**Why:** Floating to integer is a narrowing conversion, and narrowing is banned only in list-initialization. (C) is list-initialization from a `double`, so it is ill-formed. (A) and (B) perform the same conversion with `=` and parentheses, which is allowed and truncates to 3. (D) is also list-initialization, but from the `int` constant 3, which needs no conversion.

### Question 2 [warmup] ([conv.array], [conv.bool], [over.ics.rank])

What does this program print?

```cpp
#include <cstdio>
#include <string>

void f(bool)        { std::puts("bool"); }
void f(std::string) { std::puts("string"); }

int main() { f("hello"); }
```

A. `bool`
B. `string`
C. Nothing: the call is ambiguous, so the program is ill-formed
D. Implementation-defined

**Answer (A):** `bool`

**Why:** The literal decays to `const char*` and then undergoes a boolean conversion to `bool`: a standard conversion sequence. Reaching `std::string` needs its converting constructor, a user-defined conversion sequence. A standard conversion sequence always ranks better than a user-defined one, so `f(bool)` wins and there is no ambiguity.

### Question 3 [warmup] ([conv.fpprom], [conv.fpint], [over.ics.scs])

What does this program print?

```cpp
#include <cstdio>

void f(long)   { std::puts("long"); }
void f(double) { std::puts("double"); }

int main() {
  float x = 1.0f;
  f(x);
}
```

A. `long`
B. Nothing: the call is ambiguous, so the program is ill-formed
C. Implementation-defined
D. `double`

**Answer (D):** `double`

**Why:** `float` to `double` is the floating-point promotion, while `float` to `long` is a floating-integral conversion. A promotion ranks better than a conversion, so `f(double)` is chosen. The ambiguity is what you get with a `short` argument: `short` to `long` and `short` to `double` are both conversions, and neither is better.

### Question 4 [tricky] ([class.conv], [dcl.init.general], [over.match.list])

Which of these declarations are well-formed?

```cpp
#include <string>

struct Name {
  Name(std::string) {}
};

Name n1 = "Ada";
Name n2("Ada");
Name n3 = {"Ada"};
```

A. All three
B. Only `n2` and `n3`
C. Only `n2`
D. Only `n1` and `n2`

**Answer (B):** Only `n2` and `n3`

**Why:** `n1` is copy-initialization from `const char[4]`, which needs a single implicit conversion all the way to `Name`: `const char*` to `std::string` and then `std::string` to `Name`, two user-defined conversions, so it is ill-formed. `n2` and `n3` select `Name`'s constructor by overload resolution, so the only implicit conversion left is the argument to `std::string`, which needs just one. Copy-list-initialization is the tempting exception people forget: it calls the constructor directly too.

### Question 5 [tricky] ([dcl.init.list], [expr.const])

With `CHAR_BIT == 8`, which of these braced initializations are well-formed?

```cpp
void demo(int i) {
  char c1{i};
  constexpr int k = 10;
  char c2{k};
  constexpr int big = 300;
  signed char c3{big};
}
```

A. All three: each value fits or is converted modulo 2^8
B. `c1` and `c2`
C. Only `c2`
D. `c2` and `c3`

**Answer (C):** Only `c2`

**Why:** `int` to `char` is narrowing unless the source is a constant expression whose value fits. `i` is not a constant expression, so `c1` is ill-formed even though 10 would fit at run time; GCC only warns about it by default, while Clang rejects it. `k` is a constant 10, so `c2` is fine. `big` is a constant, but 300 does not fit in an 8-bit `signed char`, so `c3` is ill-formed.

### Question 6 [tricky] ([dcl.init.list], [conv.bool], [expr.unary.op])

In C++20 or later, which of these initializations are ill-formed?

```cpp
void demo(int* p) {
  bool b1 = p;
  bool b2{p};
  bool b3 = !!p;
}
```

A. Only `b2`
B. `b1` and `b2`
C. None of them
D. Only `b1`

**Answer (A):** Only `b2`

**Why:** P1957, adopted for C++20 as a defect report, made pointer and pointer-to-member to `bool` a narrowing conversion, so it is banned in the braces of `b2`. It is still an ordinary implicit boolean conversion, so `b1` is fine. `b3` contextually converts `p` for `!` and then initializes from a `bool`, which needs no conversion at all. GCC diagnoses `b2` only with a warning by default; Clang rejects it.

### Question 7 [standardese] ([expr.const], [except.spec], [dcl.pre], [stmt.if])

In C++23, which declaration is ill-formed?

A. `static_assert(2);`
B. `bool b = 2;`
C. `void g() { if constexpr (2) {} }`
D. `void f() noexcept(2);`

**Answer (D):** `void f() noexcept(2);`

**Why:** The operand of a `noexcept` specifier is a contextually converted constant expression of type `bool`, and converted constant expressions forbid narrowing; `int` 2 to `bool` is narrowing because `bool` cannot represent 2. C++23 (P1401) relaxed exactly two such contexts, `static_assert` and `if constexpr`, to plain contextual conversion, so the first and third options are valid. `bool b = 2;` is ordinary copy-initialization, where narrowing is allowed.

### Question 8 [standardese] ([conv.ptr], [lex.icon])

In C++23, what does the standard say about this code?

```cpp
const int zero = 0;
int* p = zero;
```

A. Well-formed: `zero` is an integral constant expression equal to zero
B. Ill-formed: `zero` is not a null pointer constant
C. Well-formed, but `p` holds an unspecified pointer value
D. Implementation-defined

**Answer (B):** Ill-formed: `zero` is not a null pointer constant

**Why:** Since C++11 (CWG 903), a null pointer constant is an integer literal with value zero or a prvalue of type `std::nullptr_t`. `zero` is a constant expression, but it is not a literal, and there is no other conversion from `int` to `int*`, so the initialization is ill-formed. The first option describes the C++03 rule, under which any integral constant expression evaluating to zero qualified.

# Casts and cv-qualifiers

> What const and volatile actually guarantee, why multi-level pointer conversions restrict const, and how to pick the narrowest C++ cast without breaking strict aliasing.

- **Source:** C++ Atlas (https://cppatlas.com/topics/casts-and-qualifiers)
- **Track:** Types and initialization
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [dcl.type.cv] (https://eel.is/c++draft/dcl.type.cv), [conv.qual] (https://eel.is/c++draft/conv.qual), [expr.static.cast] (https://eel.is/c++draft/expr.static.cast), [expr.const.cast] (https://eel.is/c++draft/expr.const.cast), [expr.reinterpret.cast] (https://eel.is/c++draft/expr.reinterpret.cast), [expr.dynamic.cast] (https://eel.is/c++draft/expr.dynamic.cast), [expr.cast] (https://eel.is/c++draft/expr.cast), [bit.cast] (https://eel.is/c++draft/bit.cast), [basic.lval] (https://eel.is/c++draft/basic.lval)
- **cppreference links:** [cv type qualifiers](https://en.cppreference.com/w/cpp/language/cv), [static_cast conversion](https://en.cppreference.com/w/cpp/language/static_cast), [const_cast conversion](https://en.cppreference.com/w/cpp/language/const_cast), [reinterpret_cast conversion](https://en.cppreference.com/w/cpp/language/reinterpret_cast), [dynamic_cast conversion](https://en.cppreference.com/w/cpp/language/dynamic_cast), [Explicit type conversion](https://en.cppreference.com/w/cpp/language/explicit_cast), [std::bit_cast](https://en.cppreference.com/w/cpp/numeric/bit_cast), [std::as_const](https://en.cppreference.com/w/cpp/utility/as_const)
- **Prerequisites:** initialization-forms, type-deduction-auto-decltype

C++ developers often treat `const` as a statement about hardware immutability and reach for casts whenever the compiler complains about types. Both habits invert how the language actually works. Qualifiers describe permissions along a specific access path or object definition, and every named cast is a contract specifying exactly which type-system boundary you are crossing—and what invariants you promise not to violate.

## What const and volatile actually promise

A cv-qualifier (`const`, `volatile`, or both) attaches to a type, not merely a variable name. When you declare an object `const int limit = 64;`, the object itself is a **const object** (`[dcl.type.cv]`). Attempting to modify `limit` by any means—even after casting away `const`—is undefined behavior, and the compiler is free to fold `limit` into immediate instructions or place it in read-only memory.

By contrast, when you take `const int& view = counter;` on a non-const `int counter = 0;`, `const` restricts only that **access path**. Other aliases (`counter` or `int*`) may still mutate the object, so the compiler cannot assume a `const T&` parameter never changes across function calls unless it proves no mutable alias exists.

> **Mental model.** A pointer-to-const or reference-to-const is a read-only window onto an object, not a promise that the underlying object itself is immutable.

Two keywords frequently misunderstood alongside `const` serve narrow, distinct roles:

- **`mutable`**: Applies to non-static, non-reference, non-const class data members. It permits modifying logical state—such as a memoized cache or an internal `std::mutex`—inside a `const`-qualified member function, even when the enclosing object is genuinely `const`.
- **`volatile`**: Instructs the compiler that reads and writes through this glvalue are observable side effects that must not be cached in registers, reordered across other volatile accesses, or optimized away. It exists for memory-mapped hardware registers, `std::sig_atomic_t` signal handlers, and `setjmp`/`longjmp` locals. It provides **no atomicity**, **no memory fences**, and **no thread-safety guarantees**.

## Qualification conversions and the const T** trap

Adding `const` at the top level of a pointer (`int*` to `const int*`) is always safe because it only removes write permission through the new pointer. Multi-level pointers obey a stricter rule under `[conv.qual]`: an implicit conversion from `int**` to `const int**` is **ill-formed**, whereas `int**` to `const int* const*` succeeds.

The reason is memory safety without casts. Suppose `int**` could convert implicitly to `const int**`:

```cpp
void sneaky(const int** pp, const int* target) {
    *pp = target; // Stores pointer-to-const into caller's int*!
}

void demo() {
    const int immutable = 42;
    int* p = nullptr;
    // sneaky(&p, &immutable); // Rejected by [conv.qual]: int** -> const int**
    const int* const* safe_view = &p; // Allowed: outer pointer is also const
    (void)safe_view;
}
```

If `sneaky(&p, &immutable)` compiled, `p` (whose type is `int*`) would end up pointing at `immutable`, letting `*p = 99;` silently overwrite a `const int` object without a single cast. Under `[conv.qual]`, whenever `const` or `volatile` is added at indirection depth `k > 0`, every outer indirection level from `1` up to `k - 1` must also be `const`-qualified.

When you want to add `const` to an lvalue expression explicitly—for instance, to force a `const` overload or prevent a range-for loop from detaching a copy-on-write container—prefer `std::as_const(obj)` from `<utility>` over `const_cast`. `std::as_const` returns `const T&` and explicitly deletes its rvalue overload (`const T&& = delete`) so you never bind a temporary accidentally.

## Named C++ casts: choosing the narrowest tool

C++ splits explicit conversions into four specialized operators plus `std::bit_cast` so readers and compilers can verify intent at the call site.

| Cast operator | Checks or work performed | Touches cv? | Adjusts base/derived offset? | Primary failure mode |
| --- | --- | --- | --- | --- |
| `static_cast` | Compile-time inverse of implicit conversions and explicit constructors | No | Yes | Unchecked downcast to wrong dynamic type causes UB |
| `const_cast` | Adds or strips `const` and `volatile` on pointers or references | Yes | No | Writing to an object originally defined as `const` causes UB |
| `dynamic_cast` | Runtime RTTI check across polymorphic class hierarchies | No | Yes | Returns `nullptr` for pointers or throws `std::bad_cast` for references |
| `reinterpret_cast` | Bit-pattern or unrelated pointer/integer type reinterpretation | No | No | Strict-aliasing UB on dereference if dynamic type mismatches |
| `std::bit_cast` | Value-preserving copy of object representation bytes (`sizeof` equal) | N/A | N/A | Requires trivially copyable source and destination types |
| C-style `(T)x` | Tries `const`, `static`, `static+const`, `reinterpret`, `reinterpret+const` | Yes | Only if `static_cast` matches | Silently falls back to `reinterpret_cast` or private-base cast |

Use **`static_cast`** for well-defined conversions: numeric narrowing (`static_cast<int>(ratio)`), recovering a typed pointer from `void*`, invoking an `explicit` constructor, or casting a base pointer to a known derived type when you already proved the dynamic type by external invariants. Note that for scoped enumerations (`enum class`), `std::to_underlying(e)` from `<utility>` (C++23) cleanly replaces `static_cast<std::underlying_type_t<E>>(e)`.

Use **`const_cast`** solely to interface with legacy non-const-correct APIs when you know the target object is genuinely mutable, or inside non-const overloads forwarding to a `const` helper (paired with `std::as_const`).

> **Pitfall.** Using `const_cast` to strip `const` and write to an object that was defined `const` (such as `const int x = 1;`) is immediate undefined behavior under `[dcl.type.cv]`, even if the write executes on mutable stack memory.

Use **`dynamic_cast`** when traversing a polymorphic hierarchy (a class with at least one virtual function) and the dynamic type is unknown until runtime—including **cross-casts** between sibling bases in multiple inheritance. Downcasting a pointer yields `nullptr` on mismatch; downcasting a reference throws `std::bad_cast`.

## Why C-style casts and reinterpret_cast hide bugs

The C-style cast `(Target)expr` and function-style cast `Target(expr)` are dangerous because `[expr.cast]` defines them as an ordered fallback chain: `const_cast`, then `static_cast`, then `static_cast` followed by `const_cast`, then `reinterpret_cast`, and finally `reinterpret_cast` followed by `const_cast`. Worse still, `(Target)expr` is explicitly permitted to bypass access control and cast between a derived class and an **inaccessible private or protected base class**, adjusting the pointer offset cleanly where `static_cast` would refuse to compile.

If an include disappears and `Derived` becomes an incomplete forward-declared type, `static_cast<Base*>(d)` fails to compile immediately, whereas `(Base*)d` silently switches from a `static_cast` (which adjusts multiple-inheritance `this` offsets) to a raw `reinterpret_cast` (which leaves the numerical address untouched and corrupts memory).

`reinterpret_cast` itself grants narrow guarantees. Converting `T*` to `U*` and back to `T*` preserves the original pointer value provided `U`'s alignment requirement is no stricter than `T`'s. Actually **dereferencing** that `U*`, however, collides with strict aliasing.

> **Standardese.** Under `[basic.lval]`, reading or writing an object through a glvalue whose type is unrelated to the object's dynamic type—outside cv/signed variations, base subobjects, or `char` / `unsigned char` / `std::byte`—is undefined behavior.

## Safe bit-punning and modern helpers

Inspecting the raw bytes or IEEE-754 representation of a `float` via `*reinterpret_cast<std::uint32_t*>(&f)` violates `[basic.lval]` because no `uint32_t` object exists at `&f`. In C++20 and later, `<bit>` provides `std::bit_cast<To>(from)`, which copies the source object representation into a brand-new `To` object, works in `constexpr` contexts, and requires zero intermediate pointers.

```cpp
#include <bit>
#include <cstdint>
#include <utility>

enum class Mode : std::uint8_t { Fast = 1, Safe = 2 };

constexpr std::uint32_t ieee_bits = std::bit_cast<std::uint32_t>(1.0f);
static_assert(ieee_bits == 0x3f800000u);

struct Base { virtual ~Base() = default; };
struct Derived : Base { int tag = 7; };

void inspect(Base* b, int& mutable_val, Mode m) {
    if (auto* d = dynamic_cast<Derived*>(b)) {
        d->tag = 9;
    }
    const int& ro = std::as_const(mutable_val);
    const_cast<int&>(ro) = 12; // Well-defined: mutable_val is non-const

    auto raw_mode = std::to_underlying(m); // std::uint8_t{1}
    (void)raw_mode;
}
```

When targeting pre-C++20 codebases, `std::memcpy` into a stack-allocated destination object provides the same aliasing-safe semantics as `std::bit_cast`, and modern optimizing compilers fold it into a single register move.

## What to remember

- `const` on an object makes mutation undefined behavior; `const` on a reference or pointer only restricts that access path.
- `volatile` inhibits compiler access elision and reordering for hardware or signal I/O, not data races between threads.
- `[conv.qual]` rejects `T**` to `const T**` to stop non-const pointers from silently aliasing `const` objects; `const T* const*` is the safe conversion.
- Prefer `static_cast`, `const_cast`, `dynamic_cast`, `std::as_const`, `std::to_underlying`, and `std::bit_cast` over C-style casts and `reinterpret_cast` type punning.

## Concept Map Outline

- **Casts and cv-qualifiers:** Qualifiers define access permissions while C++ casts constrain which type invariants you cross.
  - **cv-qualifiers:** const and volatile attach to types and distinguish object immutability from read-only views.
    - **const object vs view:** Modifying a const-defined object is UB, whereas const T& only restricts one access path.
    - **mutable members:** mutable permits updating internal caches or mutexes inside const member functions.
    - **volatile semantics:** volatile prevents compiler register caching for MMIO and signals without adding thread safety.
  - **Qualification conversions:** Multi-level pointers require outer const qualifiers whenever inner pointees gain const.
    - **const T** rejection:** Implicitly converting T** to const T** would allow storing a const pointer into a mutable pointer.
    - **std::as_const:** Adds const to an lvalue safely and deletes its rvalue overload to prevent dangling.
  - **Named cast operators:** Each named cast isolates a distinct operation so compilers catch unintended conversions.
    - **static_cast:** Performs compile-time checked conversions and adjusts base-derived offsets without RTTI.
    - **const_cast:** Adds or removes const or volatile, safe only when the underlying object is non-const.
    - **dynamic_cast:** Verifies polymorphic inheritance at runtime, returning nullptr or throwing std::bad_cast.
    - **reinterpret_cast:** Reinterprets pointer or integer bit patterns without adjusting class subobject offsets.
  - **C-style cast hazards:** C-style casts fall back silently to reinterpret_cast and bypass base-class access specifiers.
    - **Incomplete type trap:** Forward-declared classes turn a C-style cast from offset-adjusting to bitwise reinterpretation.
    - **Private base bypass:** Unlike static_cast, a C-style cast is allowed to cast to an inaccessible base class.
  - **Strict aliasing and bit_cast:** Object representations must be reinterpreted through safe copies rather than unrelated pointers.
    - **Strict aliasing rule:** Dereferencing an unrelated pointer type causes UB outside char, unsigned char, and std::byte.
    - **std::bit_cast:** Copies bytes into a fresh trivially copyable value in constexpr code with zero aliasing UB.
    - **std::to_underlying:** C++23 utility converting a scoped enum cleanly to its underlying integer type.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.static.cast], [utility.underlying])

Which cast operator should you use to convert a scoped enum class value into its underlying integer type in C++23?

```cpp
enum class Status : std::uint16_t { Ok = 0, Busy = 1 };
```

A. std::to_underlying(Status::Busy) or static_cast<std::uint16_t>(Status::Busy)
B. reinterpret_cast<std::uint16_t>(Status::Busy)
C. const_cast<std::uint16_t>(Status::Busy)
D. dynamic_cast<std::uint16_t>(Status::Busy)

**Answer (A):** std::to_underlying(Status::Busy) or static_cast<std::uint16_t>(Status::Busy)

**Why:** Scoped enums do not implicitly convert to integers, so static_cast or C++23 std::to_underlying (which wraps static_cast<std::underlying_type_t<E>>) is the idiomatic, type-safe conversion. reinterpret_cast rejects non-pointer enum-to-int conversions.

### Question 2 [warmup] ([dcl.type.cv], [intro.races])

What guarantee does qualifying a variable as volatile provide in multi-threaded C++ code?

A. Atomic reads and writes without tearing
B. Release/acquire memory ordering across CPU cores
C. Neither atomicity nor cross-thread ordering; it only prevents compiler access elision and reordering of volatile accesses
D. Hardware cache-line flushing on every store

**Answer (C):** Neither atomicity nor cross-thread ordering; it only prevents compiler access elision and reordering of volatile accesses

**Why:** volatile tells the compiler each access is an observable side effect for MMIO or signal handlers, forbidding register caching. It provides zero atomicity or happens-before guarantees across threads; use std::atomic for concurrency.

### Question 3 [tricky] ([conv.qual])

Why does the assignment `const int** pp = &p;` fail to compile when `p` has type `int*`, whereas `const int* const* pp = &p;` compiles?

```cpp
int* p = nullptr;
// const int** bad = &p;
const int* const* ok = &p;
```

A. Because pointer-to-pointer types never allow implicit qualification conversions
B. Because converting int** to const int** would let *pp store a const int* into p, enabling mutation of a const object through p without a cast
C. Because const int* and int* have different sizes and alignments
D. Because C++ requires reinterpret_cast whenever two pointers differ in cv-qualification

**Answer (B):** Because converting int** to const int** would let *pp store a const int* into p, enabling mutation of a const object through p without a cast

**Why:** Under [conv.qual], adding const at an inner pointer level requires every outer level up to the top to also become const. Otherwise *pp = &some_const_int would leave the non-const int* p pointing at a const object.

### Question 4 [tricky] ([dcl.type.cv], [expr.const.cast])

What happens when `modify(x)` executes on a variable defined as `const int x = 10;`?

```cpp
void modify(const int& ref) {
    const_cast<int&>(ref) = 20;
}
const int x = 10;
modify(x);
```

A. x reliably becomes 20 because const_cast removes the reference's constness
B. Compilation fails because const_cast only accepts pointers, not references
C. Undefined behavior, because modifying an object that was originally defined const is UB regardless of const_cast
D. Implementation-defined write that succeeds whenever x has automatic storage duration

**Answer (C):** Undefined behavior, because modifying an object that was originally defined const is UB regardless of const_cast

**Why:** const_cast only removes const from the access path; [dcl.type.cv] states that any attempt to modify an object defined as const through a non-const glvalue results in undefined behavior.

### Question 5 [standardese] ([expr.cast], [expr.static.cast])

Given `struct PrivDerived : private Base {};` and `PrivDerived* pd`, how do `static_cast<Base*>(pd)` and `(Base*)pd` differ?

```cpp
struct Base { int a; };
struct PrivDerived : private Base {};
PrivDerived d;
```

A. Both fail to compile because Base is an inaccessible private base class
B. static_cast<Base*>(&d) fails to compile, whereas (Base*)&d is well-formed and adjusts the pointer to the private Base subobject
C. Both succeed and invoke reinterpret_cast without adjusting subobject offsets
D. static_cast<Base*>(&d) succeeds via friendship rules while (Base*)&d calls reinterpret_cast

**Answer (B):** static_cast<Base*>(&d) fails to compile, whereas (Base*)&d is well-formed and adjusts the pointer to the private Base subobject

**Why:** Under [expr.cast], an explicit C-style cast performs the same subobject pointer adjustment as static_cast even when the base class is private or protected—bypassing access checking that static_cast strictly enforces.

### Question 6 [standardese] ([basic.lval], [bit.cast])

Which technique inspects the bit pattern of a `float` as a `std::uint32_t` without violating `[basic.lval]` strict aliasing rules?

```cpp
float f = 1.5f;
```

A. auto bits = *reinterpret_cast<std::uint32_t*>(&f);
B. union U { float f; std::uint32_t u; } x{f}; auto bits = x.u;
C. auto bits = *(std::uint32_t*)(void*)&f;
D. auto bits = std::bit_cast<std::uint32_t>(f);

**Answer (D):** auto bits = std::bit_cast<std::uint32_t>(f);

**Why:** Reading a float through a std::uint32_t* via reinterpret_cast or C-style cast violates strict aliasing ([basic.lval]), and reading an inactive union member is UB in C++. std::bit_cast<std::uint32_t>(f) (or std::memcpy) creates a valid std::uint32_t object from the bytes.

# Casts

> Each named cast is a narrow permission. static_cast performs conversions the type system can check, const_cast only changes qualifiers, reinterpret_cast reuses a value's bits or address under a different type, and dynamic_cast asks the object at run time. A C-style cast tries them in a fixed order and takes the first that compiles.

- **Source:** C++ Atlas (https://cppatlas.com/topics/casts)
- **Track:** Types and initialization
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [expr.static.cast] (https://eel.is/c++draft/expr.static.cast), [expr.const.cast] (https://eel.is/c++draft/expr.const.cast), [expr.reinterpret.cast] (https://eel.is/c++draft/expr.reinterpret.cast), [expr.dynamic.cast] (https://eel.is/c++draft/expr.dynamic.cast), [expr.cast] (https://eel.is/c++draft/expr.cast), [expr.type.conv] (https://eel.is/c++draft/expr.type.conv), [bit.cast] (https://eel.is/c++draft/bit.cast), [dcl.type.cv] (https://eel.is/c++draft/dcl.type.cv), [expr.type] (https://eel.is/c++draft/expr.type)
- **cppreference links:** [static_cast conversion](https://en.cppreference.com/w/cpp/language/static_cast), [const_cast conversion](https://en.cppreference.com/w/cpp/language/const_cast), [reinterpret_cast conversion](https://en.cppreference.com/w/cpp/language/reinterpret_cast), [dynamic_cast conversion](https://en.cppreference.com/w/cpp/language/dynamic_cast), [Explicit type conversion (C-style and functional casts)](https://en.cppreference.com/w/cpp/language/explicit_cast), [std::bit_cast](https://en.cppreference.com/w/cpp/numeric/bit_cast)
- **Prerequisites:** implicit-conversions, value-categories, const-volatile-and-qualifiers

## The one idea

A cast is a request to treat an expression as having another type, and C++ splits that request into four kinds of permission so that each cast states which rule it is relying on.

- `static_cast` performs conversions the compiler can check from the types alone, including some that are unsafe at run time.
- `const_cast` adds or removes `const` and `volatile`, and nothing else.
- `reinterpret_cast` reuses an address or a bit pattern under another type, and never changes the value representation.
- `dynamic_cast` consults the object's dynamic type at run time and can fail.

The C-style cast `(T)e` and the functional cast `T(e)` are not a fifth kind. They try the named casts in a fixed order and quietly use the first that is well-formed, which is why they are dangerous.

> **Mental model.** Choose the weakest cast that does the job. If the cast compiles, you know which rule applies; if a stronger cast is needed, the compiler forces you to spell it.

## static_cast: conversions the type system can check

[expr.static.cast] allows four broad groups of conversions.

1. Anything direct-initialization could do: `static_cast<T>(e)` is valid if `T t(e);` would be, and it means the same thing. This includes explicit constructors and explicit conversion functions.
2. Conversion to `void`, which discards a value.
3. The reverse of many standard conversions: integer or floating to enumeration, `void*` to `T*`, base pointer or reference to derived, and pointer to member of base to pointer to member of derived. It cannot reverse lvalue-to-rvalue, array-to-pointer, function-to-pointer or the boolean conversion, and it never removes `const`.
4. A glvalue to an rvalue reference, `static_cast<T&&>(x)`, which is what `std::move` is.

The downcast in group 3 is checked only statically. If a `Base*` does not actually point to a `Base` subobject of a `Derived`, the cast itself has undefined behavior, before anyone dereferences the result. The base must also not be virtual: downcasting through a virtual base needs `dynamic_cast`.

```cpp
struct Base {};
struct Derived : Base { int extra = 0; };

constexpr bool bad() {
  Base b;
  Derived* d = static_cast<Derived*>(&b);  // undefined: b is not inside a Derived
  (void)d;
  return true;
}
// static_assert(bad());  // Clang rejects it: "cannot cast object of dynamic type
//                        // 'Base' to type 'Derived'"; GCC 16 misses this one
```

Casting an integer to an enumeration without a fixed underlying type is undefined if the value is outside the enumeration's range, since C++17; the enumerations-and-unions topic has the details. `static_cast<void*>` and back to the original type is always a round trip.

## const_cast and when writing is undefined

`const_cast` changes only cv-qualification, at any level of a pointer or pointer-to-member type, or on a reference. It can also turn an lvalue into an xvalue with `const_cast<T&&>`. It cannot change any other part of the type.

Removing `const` is always allowed; what you do next may not be. [dcl.type.cv] says any attempt to modify a **const object** during its lifetime is undefined behavior. The question is whether the object itself was created const, not whether the path you reached it through was.

```cpp
constexpr bool writes_const() {
  const int x = 1;
  *const_cast<int*>(&x) = 2;   // undefined: x is a const object
  return true;
}
// static_assert(writes_const());  // rejected: modifying a const object

constexpr bool writes_nonconst() {
  int y = 1;
  const int& r = y;
  const_cast<int&>(r) = 2;     // fine: y was never const
  return y == 2;
}
static_assert(writes_nonconst());
```

String literals are const arrays, so writing through a `const_cast` of one is undefined too. The legitimate uses are calling an old API that takes `char*` but does not write, and implementing a non-const member function in terms of its const twin with `std::as_const` and a `const_cast` on the result, where the object is known to be non-const.

> **Pitfall.** Compilers assume const objects never change. After `const int n = 1;` and a write through a `const_cast`, later reads of `n` are often folded to 1, so a debugger and the program disagree. That is one possible outcome of undefined behavior, not a rule you can rely on.

## reinterpret_cast: same bits, different type

`reinterpret_cast` exists for conversions the type system cannot check. [expr.reinterpret.cast] lists them exhaustively:

- a pointer to an integer type large enough to hold it, and an integer back to a pointer; a round trip through `std::uintptr_t` gives the original pointer;
- an object pointer to another object pointer type, defined as `static_cast<cv T*>(static_cast<cv void*>(p))`, so the address is unchanged;
- a function pointer to another function pointer type, where calling through the wrong type is undefined;
- a conversion between object and function pointers, which is conditionally-supported;
- an lvalue to a reference type, `reinterpret_cast<T&>(x)`, which means `*reinterpret_cast<T*>(&x)`;
- a pointer to member to another pointer to member of the same kind.

It cannot cast away `const`, it cannot convert between arithmetic values (`reinterpret_cast<int>(3.0)` is ill-formed), and it is never allowed in a constant expression. Producing the new pointer is usually fine; reading through it is governed by the aliasing rules, which the strict-aliasing-and-undefined-behavior topic covers.

## dynamic_cast: asking the object

`dynamic_cast<T*>(p)` and `dynamic_cast<T&>(r)` look at the most derived object at run time. An upcast to an accessible, unambiguous base is just the implicit conversion and works on any class. Every other use requires the operand's class to be **polymorphic**, meaning it has at least one virtual function.

- A **downcast** succeeds if the operand refers to a public base subobject of exactly one `T` object inside the most derived object.
- Otherwise a **cross-cast** succeeds if the operand is a public base of the most derived object and that object has a public, unambiguous base `T`, even if `T` is unrelated to the operand's static type.
- `dynamic_cast<void*>(p)` returns a pointer to the most derived object, which can differ from `static_cast<void*>(p)` under multiple inheritance.
- On failure, the pointer form returns a null pointer and the reference form throws `std::bad_cast`. A null pointer operand gives a null result.

A private or ambiguous base makes the run-time check fail rather than the program ill-formed, because the check is about the dynamic object, not the static types.

```cpp
#include <cstdio>
#include <typeinfo>

struct A { virtual ~A() = default; };
struct B { virtual ~B() = default; };
struct C : A, B {};

int main() {
  C c;
  A* pa = &c;
  B* pb = dynamic_cast<B*>(pa);                     // cross-cast: succeeds
  std::printf("%d\n", dynamic_cast<void*>(pb) == static_cast<void*>(&c));  // 1
  std::printf("%d\n", static_cast<void*>(pb) == static_cast<void*>(&c));   // 0 on common ABIs
  A a;
  try { (void)dynamic_cast<C&>(a); }
  catch (const std::bad_cast&) { std::puts("bad_cast"); }  // printed
}
```

During construction and destruction, `dynamic_cast` treats the object as having the type of the class whose constructor or destructor is running, so a cast to a more derived class fails there.

## C-style and functional casts

[expr.cast] defines `(T)e` as the first of these that is well-formed:

1. `const_cast<T>(e)`
2. `static_cast<T>(e)`
3. `static_cast` followed by `const_cast`
4. `reinterpret_cast<T>(e)`
5. `reinterpret_cast` followed by `const_cast`

The static_cast steps also get one extra power: they may convert to or from a base class that is **inaccessible**, which no named cast can do. So `(Base*)&d` performs a correct, address-adjusting derived-to-base conversion even when `Base` is a private base.

The order hides mistakes. `(int*)p` with `p` a `const char*` cannot be a static_cast, so it silently becomes a reinterpret_cast plus a const_cast. Worse, if the classes involved are incomplete at the point of the cast, [expr.cast] makes it unspecified whether the static_cast or reinterpret_cast interpretation is used, so an include you forgot can turn a pointer-adjusting conversion into a plain reinterpretation of the address.

```cpp
struct Base { int x = 1; };
struct Other { int y = 2; };
struct Derived : Other, private Base {};

void demo() {
  Derived d;
  // Base* a = static_cast<Base*>(&d);  // ill-formed: Base is inaccessible
  Base* b = (Base*)&d;                  // OK: static_cast semantics, access ignored
  const char* s = "hi";
  int* p = (int*)s;                     // reinterpret_cast, then const_cast
  (void)b; (void)p;
}
```

The functional notation `T(e)` with a single expression means exactly `(T)e`, so `std::uintptr_t(p)` is a reinterpret_cast. `T{e}` is different: it is list-initialization, which considers only implicit conversions and rejects narrowing. `T()` value-initializes, and `T(a, b)` direct-initializes. C++23 adds `auto(x)` and `auto{x}`, which produce a decayed prvalue copy.

## std::bit_cast and the value category of a cast

C++20 added `std::bit_cast<To>(from)` in `<bit>` for the job people used to do with `reinterpret_cast` or a union: reading an object's bits as another type. Both types must be trivially copyable and of the same size. The result is a new object, so there is no aliasing problem, and it is `constexpr` unless a pointer, union, volatile member or reference is involved. If the bits do not form a valid value of `To`, the behavior is undefined. The bit-manipulation topic covers it in more depth.

```cpp
#include <bit>
#include <cstdint>

constexpr std::uint32_t one = std::bit_cast<std::uint32_t>(1.0f);
static_assert(one == 0x3f800000);  // holds wherever float is IEEE binary32
```

Every cast obeys one rule for the category of its result: an lvalue reference type gives an lvalue, an rvalue reference to an object type gives an xvalue, and any other type gives a prvalue. A prvalue of non-class type is never cv-qualified, so `static_cast<const int>(i)` has type `int`; for a class type, `static_cast<const S>(s)` keeps the `const`.

```cpp
#include <type_traits>
#include <utility>

int i = 0;
static_assert(std::is_same_v<decltype(static_cast<const int>(i)), int>);
static_assert(std::is_same_v<decltype((static_cast<int&&>(i))), int&&>);  // xvalue
static_assert(std::is_same_v<decltype((const_cast<const int&>(i))), const int&>);
```

> **Standardese.** [expr.static.cast] and its siblings each open with the same sentence: the result is an lvalue if the target is an lvalue reference type or an rvalue reference to function type, an xvalue if it is an rvalue reference to object type, and a prvalue otherwise. [expr.type] then strips cv-qualifiers from non-class prvalues.

## What to remember

- `static_cast` does what direct-initialization could, plus checked reversals of standard conversions; a wrong downcast is undefined at the cast.
- `const_cast` changes qualifiers only; writing to an object that was created const is undefined, writing to a non-const object through a const path is fine.
- `reinterpret_cast` keeps addresses and bits, cannot remove `const`, cannot convert arithmetic values, and is never constant.
- `dynamic_cast` needs a polymorphic source except for upcasts, supports cross-casts and `void*`, returns null for pointers and throws `std::bad_cast` for references.
- A C-style cast tries const, static, static plus const, reinterpret, reinterpret plus const, and may ignore base-class access.
- `T(e)` equals `(T)e`; `T{e}` is list-initialization and rejects narrowing.
- `std::bit_cast` copies bits into a new object of the same size and is usually constexpr.
- Cast results are lvalues for `T&`, xvalues for `T&&`, prvalues otherwise; non-class prvalues lose cv.

## Concept Map Outline

- **Casts:** Four named casts with narrow permissions, plus C-style and functional casts that try them in order.
  - **static_cast:** Conversions the compiler can check from the types alone.
    - **Direct-init power:** Valid when T t(e); would be, including explicit constructors and conversion functions.
    - **Reverse conversions:** void* to T*, int or float to enum, base to derived; never removes const.
    - **Wrong downcast is UB:** If the Base is not inside a Derived, the cast itself is undefined.
    - **To T&&:** Turns a glvalue into an xvalue; this is what std::move does.
  - **const_cast:** Adds or removes const and volatile, and changes nothing else.
    - **Const objects:** Writing to an object created const is undefined, even after a valid const_cast.
    - **Const paths:** Writing to a non-const object reached through a const pointer is fine.
    - **as_const idiom:** Implement a non-const member via the const one, then const_cast the result.
  - **reinterpret_cast:** Reuses an address or bits under another type.
    - **Pointer and integer:** Round trip through an integer large enough, such as uintptr_t, restores the pointer.
    - **Pointer to pointer:** Same address; reading through it is limited by the aliasing rules.
    - **Cannot do:** Cannot remove const, convert arithmetic values or appear in a constant expression.
  - **dynamic_cast:** Checks the most derived object at run time.
    - **Needs polymorphism:** Except for upcasts, the source class must have a virtual function.
    - **Failure:** Pointer form returns null; reference form throws std::bad_cast.
    - **Cross-cast:** Can reach a sibling base if the most derived object has it publicly and unambiguously.
    - **void* target:** Returns the address of the most derived object.
  - **C-style and functional:** (T)e and T(e) try the named casts in a fixed order.
    - **Order:** const, static, static then const, reinterpret, reinterpret then const.
    - **Ignores access:** Its static steps may convert to or from an inaccessible base class.
    - **Incomplete classes:** Unspecified whether static or reinterpret semantics apply, so the address may not adjust.
    - **T{e} differs:** Braces are list-initialization: implicit conversions only, no narrowing.
  - **Results and bit_cast:** Value category rules and the C++20 bit copy.
    - **Value category:** T& gives an lvalue, T&& to an object gives an xvalue, anything else a prvalue.
    - **cv on prvalues:** Non-class prvalues are never cv-qualified, so static_cast<const int> yields int.
    - **std::bit_cast (C++20):** Copies bits into a new object of the same size; trivially copyable types; often constexpr.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.const.cast], [expr.static.cast], [expr.reinterpret.cast])

Given `const int* cp`, which of these named casts to `int*` is well-formed?

```cpp
int x = 0;
const int* cp = &x;
// int* p = ???_cast<int*>(cp);
```

A. `static_cast<int*>(cp)`
B. `reinterpret_cast<int*>(cp)`
C. `const_cast<int*>(cp)`
D. `dynamic_cast<int*>(cp)`

**Answer (C):** `const_cast<int*>(cp)`

**Why:** Only `const_cast` may remove cv-qualification. `static_cast` and `reinterpret_cast` are both forbidden from casting away constness, so both are ill-formed here even though `reinterpret_cast` is often assumed to allow anything. `dynamic_cast` requires a pointer or reference to a class type.

### Question 2 [warmup] ([dcl.type.cv], [expr.const.cast])

What does the standard say about this program?

```cpp
#include <cstdio>

int main() {
  const int x = 1;
  int* p = const_cast<int*>(&x);
  *p = 2;
  std::printf("%d\n", x);
}
```

A. Undefined behavior
B. It prints `2`
C. It prints `1`, because the compiler folds `x`
D. Ill-formed: `const_cast` cannot be applied to the address of a const object

**Answer (A):** Undefined behavior

**Why:** The `const_cast` itself is valid, but `x` is a const object, and modifying a const object during its lifetime is undefined behavior. Printing `1` is a common outcome because compilers fold reads of `x` to its initializer, but it is just one possible result of undefined behavior. Had `x` been declared without `const` and reached through a `const int*`, the write would be fine.

### Question 3 [warmup] ([expr.dynamic.cast], [bad.cast])

What does this program print?

```cpp
#include <cstdio>
#include <typeinfo>

struct A { virtual ~A() = default; };
struct C : A {};

int main() {
  A a;
  try {
    C& c = dynamic_cast<C&>(a);
    (void)c;
    std::puts("ok");
  } catch (const std::bad_cast&) {
    std::puts("bad_cast");
  }
}
```

A. `ok`
B. Nothing: it is ill-formed to `dynamic_cast` to a reference
C. Undefined behavior: a reference cannot be null
D. `bad_cast`

**Answer (D):** `bad_cast`

**Why:** `a` is a complete `A` object, not part of a `C`, so the run-time check fails. There is no null reference to return, so the reference form of `dynamic_cast` throws `std::bad_cast` instead, and the handler prints `bad_cast`. The pointer form would have returned a null pointer.

### Question 4 [tricky] ([expr.static.cast])

What does the standard say about this program?

```cpp
struct Base { virtual ~Base() = default; };
struct Derived : Base { int extra = 0; };

int main() {
  Base b;
  Derived* d = static_cast<Derived*>(&b);
  (void)d;  // d is never dereferenced
}
```

A. Well-defined, as long as `d` is never dereferenced
B. Undefined behavior at the cast itself
C. `d` is a null pointer, because the cast fails
D. Ill-formed: `Base` is polymorphic, so `dynamic_cast` is required

**Answer (B):** Undefined behavior at the cast itself

**Why:** [expr.static.cast] allows a base-to-derived pointer cast only when the pointer really points to a base subobject of a `Derived`; otherwise the behavior is undefined, and that applies to the cast, not just to a later access. Only `dynamic_cast` checks and returns null. Being polymorphic does not forbid `static_cast`; it merely makes the checked alternative available.

### Question 5 [tricky] ([expr.cast], [expr.static.cast])

What does the standard say about this program?

```cpp
struct Base { int x = 1; };
struct Other { int y = 2; };
struct Derived : Other, private Base {};

int main() {
  Derived d;
  Base* b = (Base*)&d;
  return b->x;
}
```

A. Ill-formed: `Base` is an inaccessible base of `Derived`
B. The cast is a `reinterpret_cast`, so `b` points at the `Other` subobject and reading `b->x` is undefined
C. Well-formed: it is a derived-to-base conversion that ignores access, and `main` returns 1
D. Implementation-defined

**Answer (C):** Well-formed: it is a derived-to-base conversion that ignores access, and `main` returns 1

**Why:** A C-style cast tries `static_cast` before `reinterpret_cast`, and in doing so it is allowed to convert to a base class even when that base is inaccessible. So `(Base*)&d` adjusts the address to the real `Base` subobject, and `b->x` reads 1. A named `static_cast<Base*>(&d)` would be ill-formed; the C-style cast is the only way to bypass the access check, which is a reason to avoid it.

### Question 6 [tricky] ([expr.static.cast], [expr.type], [dcl.type.decltype])

What type does `T` name?

```cpp
int i = 0;
using T = decltype(static_cast<const int>(i));
```

A. `int`
B. `const int`
C. `const int&`
D. `int&&`

**Answer (A):** `int`

**Why:** Casting to a non-reference type produces a prvalue, and `decltype` of a prvalue is the plain type. [expr.type] says a prvalue of non-class type is never cv-qualified, so the `const` is dropped and `T` is `int`; GCC even warns that the qualifier is ignored. For a class type, `static_cast<const S>(s)` would keep the `const`.

### Question 7 [standardese] ([expr.dynamic.cast])

What does this program print?

```cpp
#include <cstdio>

struct A { virtual ~A() = default; int a = 0; };
struct B { virtual ~B() = default; int b = 0; };
struct C : A, B {};

int main() {
  C c;
  B* pb = &c;
  std::printf("%d\n", dynamic_cast<void*>(pb) == static_cast<void*>(&c));
}
```

A. `0`, because `pb` points at the `B` subobject
B. Implementation-defined: it depends on the class layout
C. Nothing: `dynamic_cast` to `void*` is ill-formed
D. `1`

**Answer (D):** `1`

**Why:** [expr.dynamic.cast] says that when the target is a pointer to `void`, the result is a pointer to the most derived object pointed to by the operand. The most derived object is `c`, so the comparison is guaranteed true whatever the layout. The tempting `0` is what `static_cast<void*>(pb)` would give on common ABIs, where the `B` subobject sits after the `A` subobject.

### Question 8 [standardese] ([expr.cast])

Given `const char* s`, which interpretation does [expr.cast] select for `(int*)s`?

```cpp
const char* s = "hi";
int* p = (int*)s;
```

A. `static_cast<int*>(s)`
B. `reinterpret_cast<const int*>(s)` followed by `const_cast<int*>`
C. `static_cast` followed by `const_cast`
D. None: the cast is ill-formed because no single named cast can do it

**Answer (B):** `reinterpret_cast<const int*>(s)` followed by `const_cast<int*>`

**Why:** A C-style cast takes the first well-formed interpretation from: `const_cast`, `static_cast`, `static_cast` then `const_cast`, `reinterpret_cast`, and `reinterpret_cast` then `const_cast`. There is no static conversion between `char` and `int` pointers, so the static steps fail, and `reinterpret_cast` alone cannot drop `const`. The last step succeeds, so the cast silently both reinterprets and removes `const`, which is exactly the combination a named cast would make you spell out.

# const, volatile and qualifiers

> A cv-qualifier attaches to one level of a type, and whether it is top-level or buried inside a pointer decides what it protects, what is ignored, and which conversions are safe. const promises nothing about pointees, modifying a const object is undefined, and volatile is about observable accesses, not threads.

- **Source:** C++ Atlas (https://cppatlas.com/topics/const-volatile-and-qualifiers)
- **Track:** Types and initialization
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [basic.type.qualifier] (https://eel.is/c++draft/basic.type.qualifier), [dcl.type.cv] (https://eel.is/c++draft/dcl.type.cv), [conv.qual] (https://eel.is/c++draft/conv.qual), [dcl.fct] (https://eel.is/c++draft/dcl.fct), [class.this] (https://eel.is/c++draft/class.this), [class.mfct.non.static] (https://eel.is/c++draft/class.mfct.non.static), [dcl.stc] (https://eel.is/c++draft/dcl.stc), [class.ctor.general] (https://eel.is/c++draft/class.ctor.general), [intro.abstract] (https://eel.is/c++draft/intro.abstract), [expr.ass] (https://eel.is/c++draft/expr.ass), [depr.volatile.type] (https://eel.is/c++draft/depr.volatile.type), [dcl.constexpr] (https://eel.is/c++draft/dcl.constexpr), [res.on.data.races] (https://eel.is/c++draft/res.on.data.races)
- **cppreference links:** [cv (const and volatile) type qualifiers](https://en.cppreference.com/w/cpp/language/cv), [Non-static member functions (const- and ref-qualified)](https://en.cppreference.com/w/cpp/language/member_functions), [Implicit conversions (qualification conversions)](https://en.cppreference.com/w/cpp/language/implicit_conversion), [constexpr specifier](https://en.cppreference.com/w/cpp/language/constexpr), [std::as_const](https://en.cppreference.com/w/cpp/utility/as_const)
- **Prerequisites:** implicit-conversions, value-categories

## The one idea

`const` and `volatile` are **cv-qualifiers**, and each one qualifies exactly one level of a type. In `const int* p`, the `int` is const and the pointer is not. In `int* const p`, the pointer is const and the `int` is not. Almost every rule about qualifiers depends on which level you are talking about.

A qualifier on the outermost level, the object itself, is **top-level**. It controls whether that object may be modified, and it is dropped whenever only the value matters: when copying, when deducing `auto`, and in function parameter types. A qualifier on a deeper level, such as what a pointer points to, is **low-level** and is part of the type in every context, because it protects someone else's object.

> **Mental model.** Read a declaration from the name outward, right to left: `int const* const p` is "p is a const pointer to const int". Every `const` you meet guards exactly the thing immediately to its left, or the thing to its right if nothing is on its left.

## Where qualifiers attach and where they vanish

Every non-function, non-reference type `T` has four versions: `T`, `const T`, `volatile T` and `const volatile T`. References and function types cannot be cv-qualified; if a typedef or `decltype` makes it look as if they are, the qualifier is silently ignored. Arrays are the odd case: a qualifier applied to an array type attaches to its elements, and the array type is then considered to have the same qualification, so `std::is_const_v<const int[3]>` is true.

Top-level qualifiers disappear in several places:

- **Parameters.** [dcl.fct] removes top-level cv-qualifiers when forming a function's type, so `void f(int)` and `void f(const int)` declare the same function. Inside the definition, the parameter is still const.
- **Prvalues.** A prvalue of non-class type is never cv-qualified, so a function returning `const int` really returns an `int`.
- **Deduction.** `auto x = ci;` with a `const int ci` deduces `int`, while `auto& r = ci;` deduces `const int&`; the type-deduction-auto-decltype topic has the full rules.

```cpp
void f(int);
void f(const int);         // redeclares f(int)
void f(int*);
void f(const int*);        // a different function: low-level const
void f(int* const);        // redeclares f(int*)

void f(const int x) {      // defines f(int); x is const in here
  // x = 1;                // ill-formed
  (void)x;
}
```

A default-initialized const object of class type needs a user-provided default constructor or a default member initializer for every member, so `struct W { int a; }; const W w;` is ill-formed while `struct W { int a = 0; };` is fine. A const variable at namespace scope that is not `inline`, `extern` or `volatile` has internal linkage, which the translation-units-and-linkage topic explains.

## Qualification conversions across pointer levels

The qualification conversion ([conv.qual]) adds cv-qualifiers below the top level. Adding `const` one level down is always safe: `int*` converts to `const int*`. Two levels down, the obvious conversion is banned.

```cpp
const int secret = 42;

void attack() {
  int* p = nullptr;
  // const int** pp = &p;   // ill-formed. If it were allowed:
  // *pp = &secret;         // fine: storing a const int* through const int**
  // *p = 0;                // p now points to secret: writes a const object
  int* const* ok1 = &p;          // OK
  const int* const* ok2 = &p;    // OK: the middle level is const too
  (void)ok1; (void)ok2;
}
```

```text
  int**           ->  const int**          banned: middle level still writable
  int**           ->  const int* const*    allowed: every level above is const
  int**           ->  int* const*          allowed: const only one level down
  level:   0  1  2        (0 is the outermost pointer)
```

The rule is that if a qualifier is added at some level, `const` must also be added at every level between it and the top, excluding the top level itself. Otherwise the intermediate pointer remains writable, and you could store a pointer to a const object into a slot that the original type sees as pointing to non-const.
> **Standardese.** [conv.qual] describes the rule through cv-decompositions of similar types. Since C++20 (P0388) the same machinery also lets an array of known bound convert to an array of unknown bound inside a pointer, so `int(*)[3]` converts to `const int(*)[]`.

## Const objects and undefined modification

[basic.type.qualifier] defines a **const object** as an object of const-qualified type or a non-mutable subobject of one. [dcl.type.cv] makes any attempt to modify a const object during its lifetime undefined behavior. The implementation may place such objects in read-only memory, fold their values into code, or assume they never change across function calls.

Constness belongs to the object, not to the path. Reaching a non-const object through a `const int&` and casting the const away to write is allowed; reaching a const object through any path and writing is undefined. The casts topic shows `const_cast` in both situations.

Constructors and destructors are the exception built into the rule. [class.ctor.general] says const and volatile semantics do not apply to an object under construction; they take effect when the most derived object's constructor finishes and end when its destructor starts. That is why a constructor can assign to members of an object declared `const`.

## const member functions, mutable and logical const

A non-static member function declared `const` gets `this` of type `const X*` ([class.this]), so inside it every non-static data member is accessed as const. A const member function is the only kind that can be called on a const object or through a `const X&`, and you can overload on it, which is how `operator[]` returns `const T&` for const containers and `T&` otherwise.

That const is **bitwise and shallow**. It applies to the members themselves, not to what pointer members point to. A const member function may modify the pointee of a raw pointer or `std::unique_ptr` member. The Library Fundamentals TS offers `std::experimental::propagate_const` to make constness reach through such members.

```cpp
#include <memory>

struct Buffer {
  int* raw;
  std::unique_ptr<int> owned;
  void clear() const {
    raw[0] = 0;   // OK: raw is int* const here, the int is not const
    *owned = 0;   // OK for the same reason
    // raw = nullptr;  // ill-formed: the member itself is const
  }
};
```

**Logical const** is the opposite design: the object's observable state does not change, even if some bits do. The `mutable` specifier ([dcl.stc]) marks a data member that may be modified through a const object, which is how caches, lazily computed values and mutexes live inside const member functions. `mutable` cannot be applied to a reference, a static member or a const member.

```cpp
#include <mutex>
#include <string>

class Name {
  std::string first_, last_;
  mutable std::mutex m_;
  mutable std::string full_;  // cache: logically part of the value
public:
  const std::string& full() const {
    std::lock_guard lock(m_);
    if (full_.empty()) full_ = first_ + " " + last_;
    return full_;
  }
};
```

> **Pitfall.** [res.on.data.races] promises that standard library functions do not modify objects reached only through const arguments, so callers reasonably treat const operations as safe to run concurrently. A `mutable` cache without a mutex or an atomic breaks that assumption and turns two concurrent const calls into a data race.

## volatile: observable accesses, not threads

[intro.abstract] makes every access through a volatile glvalue part of the program's observable behavior. The compiler must perform each such read and write, in program order relative to other volatile accesses, and may not merge, remove or invent them. This is for memory-mapped hardware registers, for locals that must survive `longjmp`, and for `volatile std::sig_atomic_t` flags shared with a signal handler.

`volatile` gives no atomicity and no ordering with respect to other threads. Two threads accessing a `volatile int` without synchronization, where at least one writes, is a data race and undefined; use `std::atomic`, which the atomics-and-memory-ordering topic covers.

C++20 adopted P1152 and deprecated uses of `volatile` whose meaning was unclear:

- `++` and `--` on a volatile object, which read and write but look like one access;
- using the value of a simple assignment to a volatile object, as in `a = v = 1`;
- volatile-qualified function parameters and return types;
- volatile structured bindings.

P1152 also deprecated compound assignment such as `v += 1`. P2327 restored the bitwise forms, and CWG 2654, resolved for C++23 and treated as a defect against C++20, restored all of them, so compound assignment on a volatile is not deprecated.

```cpp
volatile int reg;

void poke() {
  reg = 1;       // OK: assignment used as a statement
  reg += 2;      // OK: not deprecated since CWG 2654
  reg |= 4;      // OK
  // ++reg;      // deprecated since C++20
  // int x = (reg = 5);   // deprecated: value of a volatile assignment is used
}
```

## constexpr versus const

`const` means "this object will not be modified". `constexpr` on a variable means "this object is initialized by a constant expression and is usable in constant expressions", and it implies `const`. A `const` variable may be initialized at run time, so `const int n = read();` is const but cannot size an array.

There is an old shortcut: a const variable of integral or enumeration type initialized with a constant expression is usable in constant expressions without `constexpr`. The shortcut does not extend to floating types, so `const double d = 1.0;` cannot initialize a `constexpr double`.

`constexpr` is always top-level. `constexpr int* p = &g;` declares `p` as `int* const`, so `*p = 5` is fine, and `g` must have static storage duration for its address to be a constant expression. To make the pointee const you still write `constexpr const int* p`.

```cpp
#include <type_traits>

int g = 0;
constexpr int* p = &g;
static_assert(std::is_same_v<decltype(p), int* const>);
void set() { *p = 5; }   // OK: the pointee is not const

const int n = 4;
int arr[n];              // OK: const integral with a constant initializer
// const double d = 1.0;
// constexpr double e = d;  // ill-formed: d is not usable in constant expressions
```

For member functions the link was cut in C++14: a `constexpr` non-static member function is no longer implicitly `const`, so calling one on a const object needs an explicit `const`. Constant evaluation in depth is the constant-expressions topic's subject.

## What to remember

- Each qualifier applies to one level; top-level const protects the object, low-level const protects what it points to.
- Top-level cv is dropped in parameter types, on non-class prvalues and in `auto` deduction by value.
- `T**` does not convert to `const T**`; `const T* const*` is fine, because every intermediate level must be const.
- Modifying a const object is undefined, however you reach it; constructors and destructors are exempt.
- const member functions make members const, not pointees; `mutable` allows logical const and needs synchronization.
- `volatile` makes accesses observable but is not atomic; C++20 deprecated `++`, `--`, volatile parameters and using a volatile assignment's value, while compound assignment was restored.
- `constexpr` implies top-level const; const integral variables with constant initializers are usable in constant expressions, const doubles are not.
- Since C++14, `constexpr` member functions are not implicitly `const`.

## Concept Map Outline

- **const and volatile:** Each cv-qualifier applies to one level of a type; the level decides what it protects.
  - **Levels:** Top-level qualifies the object itself; low-level qualifies what it points to.
    - **Read right to left:** int const* const p is a const pointer to const int.
    - **Parameters drop top-level:** void f(int) and void f(const int) declare the same function.
    - **Prvalues drop cv:** A non-class prvalue is never cv-qualified, so returning const int returns int.
    - **Arrays and references:** cv on an array applies to its elements; cv on a reference or function type is ignored.
  - **Qualification conversion:** Adds cv below the top level of a pointer type.
    - **T** to const T**:** Banned: the writable middle pointer could be made to point at a const object.
    - **const T* const*:** Allowed: if a level gains const, every level above it except the top must be const.
    - **Unknown bounds (C++20):** P0388 lets int(*)[3] convert to const int(*)[].
  - **Const objects:** Objects created const, or non-mutable subobjects of them.
    - **Modification is UB:** Writing a const object is undefined, whatever path or cast reaches it.
    - **Path is irrelevant:** A non-const object reached through const T& may be written after const_cast.
    - **Under construction:** Const semantics start when the constructor finishes and stop when the destructor starts.
  - **const member functions:** this has type const X*, so members are accessed as const.
    - **Shallow const:** Pointer members become T* const; the pointees stay modifiable.
    - **mutable:** Lets a member change in a const object; not allowed on references, statics or const members.
    - **Logical const:** Observable state is unchanged even when caches or mutexes change.
    - **Thread safety:** Callers assume concurrent const calls are safe, so a mutable cache needs a lock or atomic.
  - **volatile:** Accesses through volatile glvalues are observable behavior.
    - **Not atomic:** Unsynchronized volatile accesses from two threads are a data race; use std::atomic.
    - **C++20 deprecations:** ++ and --, using a volatile assignment's value, volatile parameters, returns and bindings.
    - **Compound assignment:** Deprecated by P1152, then restored by P2327 and CWG 2654; not deprecated in C++23.
  - **constexpr vs const:** const forbids modification; constexpr also demands constant initialization.
    - **Top-level only:** constexpr int* p is int* const; the pointee is still writable.
    - **Integral shortcut:** A const integral variable with a constant initializer is usable in constant expressions.
    - **Not for doubles:** const double d = 1.0 cannot initialize a constexpr double.
    - **Members (C++14):** A constexpr member function is no longer implicitly const.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.ptr], [basic.type.qualifier])

Which two of the commented statements would be ill-formed if uncommented?

```cpp
void demo() {
  int a = 0, b = 0;
  const int* p = &a;
  int* const q = &a;
  // *p = 1;   // (1)
  // p = &b;    // (2)
  // *q = 1;    // (3)
  // q = &b;    // (4)
  (void)p; (void)q; (void)b;
}
```

A. (1) and (3)
B. (1) and (4)
C. (2) and (3)
D. (2) and (4)

**Answer (B):** (1) and (4)

**Why:** In `const int* p` the `const` qualifies the `int`, so the pointee cannot be written through `p` but `p` itself can be reseated: (1) fails, (2) is fine. In `int* const q` the `const` qualifies the pointer, so `q` cannot be reseated but the `int` can be written: (3) is fine, (4) fails. Reading each declaration right to left from the name gives the answer directly.

### Question 2 [warmup] ([dcl.stc], [basic.type.qualifier], [dcl.type.cv])

What does this program print?

```cpp
#include <cstdio>

struct Widget {
  mutable int reads = 0;
  int value = 42;
  int get() const { ++reads; return value; }
};

int main() {
  const Widget w;
  w.get();
  w.get();
  std::printf("%d\n", w.reads);
}
```

A. Nothing: `get` modifies the object but is `const`, so the program is ill-formed
B. Undefined behavior: `w` is a const object
C. `0`
D. `2`

**Answer (D):** `2`

**Why:** A `mutable` member is not part of the const object: [basic.type.qualifier] defines a const object's subobjects as const only when they are non-mutable. So `get` may increment `reads` even through `const Widget*`, and doing so on a const object is well-defined. The program prints `2`. Without `mutable`, the increment would be ill-formed, not undefined.

### Question 3 [warmup] ([dcl.fct], [over.load])

How many distinct functions do these declarations declare?

```cpp
void f(int);
void f(const int);
void f(int*);
void f(const int*);
void f(int* const);
```

A. 3
B. 5
C. 4
D. 2

**Answer (A):** 3

**Why:** When the function type is formed, top-level cv-qualifiers on parameter types are removed, so `f(const int)` redeclares `f(int)` and `f(int* const)` redeclares `f(int*)`. The `const` in `f(const int*)` is low-level, part of the pointee type, so that one is a distinct overload. That leaves `f(int)`, `f(int*)` and `f(const int*)`.

### Question 4 [tricky] ([conv.qual])

Which of these initializations are ill-formed?

```cpp
void demo() {
  int* p = nullptr;
  int** pp = &p;
  const int** a = pp;        // (A)
  const int* const* b = pp;  // (B)
  int* const* c = pp;        // (C)
  (void)a; (void)b; (void)c;
}
```

A. (B) only
B. (A) and (B)
C. (A) only
D. None of them

**Answer (C):** (A) only

**Why:** Adding `const` two levels down is only allowed if every level in between, except the outermost, becomes `const` as well. (A) leaves the middle pointer writable, so through `a` you could store the address of a `const int` into `p` and then modify it through `p`; the conversion is banned and (A) is ill-formed. (B) makes the middle level const, closing that hole, and (C) adds `const` only one level down, which is always safe.

### Question 5 [tricky] ([dcl.constexpr], [expr.const])

What does the standard say about this code?

```cpp
int g = 0;
constexpr int* p = &g;

void set() { *p = 5; }
```

A. Well-formed: `p` has type `int* const`, so the pointee is modifiable
B. Ill-formed: `constexpr` makes `*p` const
C. Ill-formed: a constexpr pointer cannot point to a non-const object
D. Undefined behavior: it modifies an object that a constant expression refers to

**Answer (A):** Well-formed: `p` has type `int* const`, so the pointee is modifiable

**Why:** `constexpr` on a variable implies `const` on that variable only, which is top-level. `p` is a constant pointer to a modifiable `int`, and `&g` is a constant expression because `g` has static storage duration. Writing through `p` modifies `g`, which is not a const object. To protect the pointee as well you would write `constexpr const int* p`.

### Question 6 [tricky] ([class.this], [expr.ref], [dcl.type.cv])

What does the standard say about calling `clear` on a `const Buffer` whose `data` points to a non-const `int` array?

```cpp
struct Buffer {
  int* data;
  void clear() const { data[0] = 0; }
};
```

A. Ill-formed: inside a const member function `data[0]` is const
B. Ill-formed unless `data` is declared `mutable`
C. Undefined behavior whenever it is called on a const `Buffer`
D. Well-formed and well-defined: only the pointer `data` itself is const inside `clear`

**Answer (D):** Well-formed and well-defined: only the pointer `data` itself is const inside `clear`

**Why:** In a const member function, `this` is `const Buffer*`, so the member `data` is accessed as `int* const`: the pointer is const, the pointee is not. Writing `data[0]` modifies an `int` that is not part of the `Buffer` object and not const, so there is no undefined behavior. This shallowness is the gap between bitwise const and logical const.

### Question 7 [standardese] ([expr.pre.incr], [expr.ass], [depr.volatile.type])

Given `volatile int v;` at namespace scope, which statement inside a function is deprecated in C++23?

A. `v += 1;`
B. `++v;`
C. `v |= 1;`
D. `int x = v;`

**Answer (B):** `++v;`

**Why:** C++20 (P1152) deprecated increment and decrement of volatile objects, and that deprecation remains in C++23. P1152 also deprecated compound assignment, but P2327 restored the bitwise forms and CWG 2654 restored the rest, so `v += 1` is not deprecated in C++23; GCC 16 and Clang 21 warn only about `++v`. Reading a volatile object is the plain, intended use.

### Question 8 [standardese] ([dcl.constexpr], [class.mfct.non.static], [over.match.funcs])

In C++23, what does the standard say about this code?

```cpp
struct S {
  int v;
  constexpr int get() { return v; }
};

constexpr S s{1};
static_assert(s.get() == 1);
```

A. Well-formed: constexpr member functions are implicitly `const`
B. Well-formed: `s` is constexpr, so `get` is evaluated at compile time regardless
C. Ill-formed: `get` is not a const member function and `s` is const
D. Ill-formed: `S` needs a constexpr constructor to be used in a constexpr variable

**Answer (C):** Ill-formed: `get` is not a const member function and `s` is const

**Why:** A `constexpr` variable is implicitly `const`, so `s.get()` needs a const member function. In C++11 a constexpr non-static member function was implicitly const, which is the tempting first option, but C++14 removed that rule, so `get` here is a non-const function and cannot be called on `s`. `S` is an aggregate, so it needs no constructor for `s{1}`.

# Initialization Forms in C++

> Decode default, value, zero, direct, copy, aggregate, and list initialization—and prevent the narrowing, most-vexing-parse, and initializer_list traps.

- **Source:** C++ Atlas (https://cppatlas.com/topics/initialization-forms)
- **Track:** Types and initialization
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [dcl.init.general] (https://eel.is/c++draft/dcl.init.general), [dcl.init.aggr] (https://eel.is/c++draft/dcl.init.aggr), [dcl.init.list] (https://eel.is/c++draft/dcl.init.list), [over.match.list] (https://eel.is/c++draft/over.match.list)
- **cppreference links:** [Initialization](https://en.cppreference.com/w/cpp/language/initialization), [Default-initialization](https://en.cppreference.com/w/cpp/language/default_initialization), [Value-initialization](https://en.cppreference.com/w/cpp/language/value_initialization), [Zero-initialization](https://en.cppreference.com/w/cpp/language/zero_initialization), [Direct-initialization](https://en.cppreference.com/w/cpp/language/direct_initialization), [Copy-initialization](https://en.cppreference.com/w/cpp/language/copy_initialization), [List-initialization](https://en.cppreference.com/w/cpp/language/list_initialization), [Aggregate initialization](https://en.cppreference.com/w/cpp/language/aggregate_initialization)
- **Prerequisites:** translation-units-and-linkage

Few languages offer as many ways to initialize a variable as C++: `int x;`, `int x{};`, `int x = 0;`, `int x(0);`, and `int x = {0};` look almost interchangeable on scalars, yet invoke completely distinct rules on classes, arrays, and containers. Knowing which syntax activates which initialization algorithm removes guesswork and eliminates silent bugs.

## The syntactic map of initialization

Under `[dcl.init.general]`, C++ selects an initialization algorithm purely from declaration syntax before checking constructors or conversions. Each form decides whether scalar bytes start zeroed, whether `explicit` constructors are eligible, and whether narrowing conversions are allowed.

| Form | Syntax example | Zeroes unmentioned scalars? | Allows `explicit` ctors? | Rejects narrowing? |
| --- | --- | --- | --- | --- |
| Default-initialization | `T x;` | No (indeterminate on stack) | Calls default ctor | Not applicable |
| Value-initialization | `T x{};` or `T()` | Yes, unless user-provided ctor | Calls default ctor | Not applicable |
| Zero-initialization | Static/thread-local baseline | Yes, recursively | No ctor invoked | Not applicable |
| Direct-initialization | `T x(a, b);` | Via chosen ctor | Yes | No |
| Copy-initialization | `T x = expr;` | Via chosen ctor | No | No |
| Direct-list-initialization | `T x{a, b};` | Empty members zeroed | Yes | Yes |
| Copy-list-initialization | `T x = {a, b};` | Empty members zeroed | No | Yes |
| Aggregate initialization | `Aggr p{.x = 1};` | Unmentioned fields `{}`-initialized | No user ctors allowed | Yes (for braced form) |

> **Mental model.** Syntax picks the ruleset first: parentheses choose direct-initialization, `=` chooses copy-initialization, braces choose list-initialization, and omitting an initializer chooses default-initialization.

## Default, value, and zero initialization

Writing `int n;` inside a function performs **default-initialization** (`[dcl.init.general]`): for non-class scalars with automatic storage duration, no initialization occurs at all, leaving `n` with an indeterminate value whose read causes Undefined Behavior (reclassified as erroneous behavior in C++26). For class types, default-initialization invokes the default constructor.

Writing `T x{};` or `T()` performs **value-initialization**. If `T` is a scalar, it is zero-initialized. If `T` is a class *without* a user-provided or deleted default constructor (including aggregates and classes with `T() = default;` declared inside the class body only when defaulted—wait carefully on that boundary: specifically, if the default constructor is neither user-provided nor deleted, the object is **zero-initialized first** and then default-initialized!). If `T` defines a user-provided default constructor `T() {}`, zero-initialization is skipped and any unmentioned scalar member remains indeterminate.

Meanwhile, **zero-initialization** applies automatically before any dynamic initialization to all variables with static or thread-local storage duration, guaranteeing deterministic starting bytes at program or thread startup.

```cpp
struct Plain {
    int count; // No user-provided constructor
};

struct Custom {
    int count;
    Custom() {} // User-provided constructor: skips pre-zeroing!
};

int check_zeroing() {
    Plain p{};  // Value-initialized: zero-initialized first -> p.count == 0
    Custom c{}; // Value-initialized: calls Custom::Custom(), c.count is indeterminate!
    (void)c;
    return p.count;
}
```

## Direct versus copy initialization

**Direct-initialization** (`T x(args);` or `static_cast<T>(expr)`) considers *all* constructors of `T`, including those marked `explicit`. **Copy-initialization** (`T x = expr;`, passing by value `f(arg)`, or `return expr;`) considers only non-`explicit` converting constructors and non-`explicit` conversion operators (`[dcl.init.general]`).

Since C++17 guaranteed copy elision, `T x = T(arg);` no longer requires an accessible copy or move constructor—the prvalue `T(arg)` initializes `x` directly in place—yet `T x = arg;` still rejects an `explicit` constructor taking `arg`.

One syntax hazard haunts direct-initialization with empty arguments: the **most vexing parse**. Because anything that *can* be parsed as a function declaration *must* be parsed as one, `Widget w();` declares a zero-argument function returning `Widget`, not a default-initialized object! Braces (`Widget w{};`) never parse as a function declaration and cleanly request value-initialization.

```cpp
struct Port {
    explicit Port(int p) : value(p) {}
    int value;
};

void check_explicit() {
    Port a(8080);   // Direct-init: explicit ctor allowed
    Port b{443};    // Direct-list-init: explicit ctor allowed
    // Port c = 80; // Error: copy-init cannot use explicit Port(int)
    // Port d = {80}; // Error: copy-list-init cannot use explicit Port(int)
    (void)a;
    (void)b;
}
```

## List initialization, narrowing, and greedy initializer_list

Braced initialization (`{...}`)—**list-initialization** (`[dcl.init.list]`)—solves the most vexing parse and enforces a vital safety rule: **narrowing conversions are ill-formed**. Converting `double` to `int`, or `int` to `char` when the source is not a constant expression whose value fits in `char`, fails to compile.

Yet list-initialization carries two infamous traps:

1. **Copy-list-initialization still checks `explicit`.** `Port p = {80};` fails to compile whenever `Port(int)` is `explicit`.
2. **Greedy `std::initializer_list` constructors.** Under `[over.match.list]`, braced overload resolution runs in two phases: first, the compiler searches *only* constructors taking `std::initializer_list`. Normal constructors are examined only if **no** viable `initializer_list` constructor exists (or if the braces are empty `{}`, which prefers the default constructor).

> **Standardese.** Under `[over.match.list]`, `T{...}` with a non-empty braced-init-list resolves in two stages: stage one considers exclusively `std::initializer_list` constructors; only when none is viable does stage two consider all constructors of `T`.

```cpp
#include <vector>

void check_vector_braces() {
    std::vector<int> five_ones(5, 1);  // Size 5: {1, 1, 1, 1, 1} (normal ctor)
    std::vector<int> two_elems{5, 1};  // Size 2: {5, 1} (greedy initializer_list!)
    std::vector<int> empty_vec{};      // Size 0: empty {} picks default ctor

    constexpr int small = 65;
    char ok_char{small};               // Valid: constant expression 65 fits in char
    // int bad{3.14};                  // Error: narrowing conversion from double to int
    (void)five_ones;
    (void)two_elems;
    (void)empty_vec;
    (void)ok_char;
}
```

> **Pitfall.** Writing `std::vector<int> v{10, 2};` constructs a 2-element vector `[10, 2]`, not ten copies of `2`. Always use parentheses `v(10, 2)` when passing element-count or capacity arguments to types that also offer an `initializer_list` constructor.

## Aggregates and C++20 changes

An **aggregate** (`[dcl.init.aggr]`) is an array or a simple class with no private or protected direct non-static data members, no virtual functions, no virtual/private/protected base classes, and—crucially in C++20—**no user-declared or inherited constructors**. Prior to C++20, writing `S() = default;` kept `S` an aggregate because the constructor was not user-provided; C++20 closed that loophole, making `S{42}` ill-formed whenever *any* constructor is explicitly declared (`= default` or `= delete` included).

C++20 also added two expressive capabilities for aggregates:

- **Designated initializers:** `Config cfg{.port = 8080, .tls = true};` initializes named members in exact declaration order. Out-of-order designators, mixing positional and designated elements, nested `.a.b`, and array `[0]` designators are ill-formed in standard C++. Unmentioned members are initialized from their default member initializers or `{}`.
- **Parenthesized aggregate initialization:** `Point p(1, 2);` works for aggregates in C++20 (without narrowing rejection), finally enabling `std::make_unique<Point>(1, 2)` and `emplace_back(1, 2)` without manually writing a constructor.

> **Pitfall.** Adding `MyPod() = delete;` or `MyPod() = default;` inside a struct in C++20 removes its aggregate status (`std::is_aggregate_v<MyPod>` becomes `false`), breaking `MyPod{1, 2}` aggregate initialization for every caller.

```cpp
#include <memory>
#include <type_traits>

struct Opts {
    int port = 80;
    bool tls = false;
};

struct NotAggregate {
    NotAggregate() = default; // User-declared ctor removes aggregate status in C++20+
    int x;
};

static_assert(std::is_aggregate_v<Opts>);
static_assert(!std::is_aggregate_v<NotAggregate>);

void check_cpp20_aggregates() {
    Opts o{.tls = true};                 // Valid: .port gets default 80, .tls becomes true
    auto p = std::make_unique<Opts>(443, true); // C++20 parenthesized aggregate init
    (void)o;
    (void)p;
}
```

## What to remember

- Declaration syntax dictates the initialization algorithm before constructor lookup runs (`T x;` default, `T x{};` value, `T x(a);` direct, `T x = a;` copy, `T x{a};` direct-list).
- Copy-initialization (`= expr` and `= {expr}`) rejects `explicit` constructors; direct forms (`(...)` and `{...}`) allow them.
- Braced list-initialization forbids narrowing conversions and avoids the most vexing parse, yet prefers `std::initializer_list` constructors whenever non-empty braces match.
- Value-initialization zeroes non-user-provided classes before calling defaulted constructors, whereas a user-provided `T() {}` skips zeroing unmentioned scalar fields.
- In C++20+, any user-declared constructor (`= default` or `= delete` included) disqualifies a class from being an aggregate, while true aggregates support ordered `.member = val` designated initializers and `(args...)` initialization.

## Concept Map Outline

- **Initialization Forms:** Declaration syntax picks the C++ initialization algorithm before constructor overload resolution runs.
  - **Default, Value & Zero:** Controls whether scalar fields start uninitialized or deterministically zeroed.
    - **Default-Initialization:** Leaves stack scalars indeterminate and invokes default constructors on classes.
    - **Value-Initialization:** Zeroes scalars and defaulted classes without user-provided constructors before calling ctor.
    - **Zero-Initialization:** Clears static and thread-local storage before any dynamic initialization executes.
  - **Direct vs. Copy:** Separates explicit constructor eligibility and resolves the most vexing parse.
    - **Direct-Initialization:** Syntax T x(args) considers all constructors including explicit ones.
    - **Copy-Initialization:** Syntax T x = expr skips explicit constructors and conversion functions.
    - **Most Vexing Parse:** Widget w(); parses as a function declaration rather than a default-initialized variable.
  - **List Initialization:** Braced syntax prevents narrowing and function-parse ambiguity while adding two-phase lookup.
    - **Narrowing Prohibition:** Rejects lossy conversions unless converting a constant expression whose value fits.
    - **Greedy initializer_list:** Non-empty braces strongly prefer std::initializer_list constructors over normal overloads.
    - **Empty Braces Rule:** Empty T x{} selects the default constructor rather than an empty initializer_list.
  - **Aggregate Initialization:** Initializes public-member arrays and constructor-free structs directly in declaration order.
    - **C++20 Aggregate Rule:** Any user-declared constructor including = default or = delete disqualifies aggregate status.
    - **Designated Initializers:** Syntax {.field = val} initializes named aggregate members strictly in declaration order.
    - **Parenthesized Aggregates:** C++20 allows T(a, b) for aggregates so emplace and make_unique work seamlessly.

## Standardese Quiz Questions

### Question 1 [warmup] ([stmt.ambig], [dcl.init.general])

Why does `Widget w();` inside a function fail when you subsequently call `w.run()`?

A. `Widget w();` declares a function named `w` taking no arguments and returning `Widget`, not a variable.
B. `Widget` has no copy constructor.
C. Parentheses can only initialize fundamental types, not classes.
D. `Widget w();` value-initializes `w` as `const`.

**Answer (A):** `Widget w();` declares a function named `w` taking no arguments and returning `Widget`, not a variable.

**Why:** Under C++'s ambiguity resolution (the most vexing parse, [stmt.ambig]), any statement that can be parsed as a declaration is parsed as a declaration—so `Widget w();` declares a function `w()`. Using `Widget w{};` or `Widget w;` constructs an object.

### Question 2 [warmup] ([over.match.list], [dcl.init.list])

Given `std::vector<int> a(4, 9);` and `std::vector<int> b{4, 9};`, what are the sizes of `a` and `b`?

A. `a` has size 2; `b` has size 4.
B. Both `a` and `b` have size 2.
C. `a` has size 4 (four 9s); `b` has size 2 (elements 4 and 9).
D. Both `a` and `b` have size 4.

**Answer (C):** `a` has size 4 (four 9s); `b` has size 2 (elements 4 and 9).

**Why:** Parentheses `a(4, 9)` invoke `std::vector(size_type count, const int& value)`, creating 4 copies of 9. Braces `b{4, 9}` trigger `[over.match.list]`, strongly preferring `std::vector(std::initializer_list<int>)` and creating 2 elements.

### Question 3 [tricky] ([dcl.init.general], [over.match.list])

Which initialization is well-formed in C++20/23 given `struct Box { explicit Box(int) {} };`?

```cpp
struct Box {
    explicit Box(int) {}
};
```

A. `Box b = 5;`
B. `Box b = {5};`
C. `void f(Box); f({5});`
D. `Box b{5};`

**Answer (D):** `Box b{5};`

**Why:** `Box b{5};` is direct-list-initialization, which allows `explicit` constructors. All three other forms (`= 5`, `= {5}`, and passing `{5}` to a parameter) are copy-initialization or copy-list-initialization, which reject `explicit` constructors under [over.match.list].

### Question 4 [tricky] ([dcl.init.general])

What is the value of `a.x` and `b.x` after running this C++23 function?

```cpp
struct A { int x; };
struct B { int x; B() {} };
void f() {
    A a{};
    B b{};
}
```

A. `a.x` is 0; `b.x` is indeterminate.
B. Both `a.x` and `b.x` are guaranteed to be 0.
C. Both `a.x` and `b.x` are indeterminate.
D. `a.x` is indeterminate; `b.x` is 0.

**Answer (A):** `a.x` is 0; `b.x` is indeterminate.

**Why:** Value-initialization (`{}`) zero-initializes `A` first because `A` has no user-provided or deleted default constructor, setting `a.x` to 0. Because `B` has a user-provided default constructor `B() {}`, value-initialization skips zero-initialization and directly runs `B()`, leaving `b.x` indeterminate.

### Question 5 [standardese] ([dcl.init.aggr])

Why does `struct S { S() = default; int x; };` fail `S s{42};` starting in C++20 even though it compiled in C++17?

A. C++20 banned `= default` on constructors inside structs.
B. C++20 changed aggregate rules from 'no user-provided constructors' to 'no user-declared constructors', disqualifying S.
C. C++20 treats `42` as narrowing when initializing `int` in an aggregate.
D. `S{42}` now calls `std::initializer_list<int>` automatically.

**Answer (B):** C++20 changed aggregate rules from 'no user-provided constructors' to 'no user-declared constructors', disqualifying S.

**Why:** In C++17, `S() = default;` inside the class body was user-declared but not user-provided, so `S` remained an aggregate. C++20 ([dcl.init.aggr]) changed the requirement to 'no user-declared or inherited constructors', so `S` is no longer an aggregate and has no constructor taking `int`.

### Question 6 [standardese] ([dcl.init.list])

Which braced conversion is NOT considered a narrowing conversion under [dcl.init.list]?

```cpp
constexpr int ok = 100;
int runtime_val = 100;
double d = 2.0;
```

A. `char c{runtime_val};`
B. `int n{d};`
C. `char c{ok};`
D. `float f{1e300};`

**Answer (C):** `char c{ok};`

**Why:** Under [dcl.init.list], converting an integer type to another integer type is NOT narrowing if the source is a constant expression whose value can be represented exactly in the target type (`constexpr int ok = 100` fits in `char`). Non-constant `runtime_val`, floating-to-integer `int{d}`, and out-of-range `float{1e300}` are all ill-formed narrowing conversions.

# Aggregates and designated initializers

> An aggregate is a type the compiler initializes member by member with no constructor in charge. Its definition was rewritten in every standard from C++11 to C++20, and C++20 added designated initializers, parenthesized aggregate initialization and deduction for aggregate templates.

- **Source:** C++ Atlas (https://cppatlas.com/topics/aggregates-and-designated-initializers)
- **Track:** Types and initialization
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [dcl.init.aggr] (https://eel.is/c++draft/dcl.init.aggr), [dcl.init.general] (https://eel.is/c++draft/dcl.init.general), [dcl.init.list] (https://eel.is/c++draft/dcl.init.list), [class.temporary] (https://eel.is/c++draft/class.temporary), [over.match.class.deduct] (https://eel.is/c++draft/over.match.class.deduct)
- **cppreference links:** [Aggregate initialization](https://en.cppreference.com/w/cpp/language/aggregate_initialization), [List-initialization](https://en.cppreference.com/w/cpp/language/list_initialization), [std::is_aggregate](https://en.cppreference.com/w/cpp/types/is_aggregate), [Class template argument deduction](https://en.cppreference.com/w/cpp/language/class_template_argument_deduction)
- **Prerequisites:** initialization-forms, reference-binding-and-temporaries

## The one idea

An aggregate is a type with no constructor in charge of it. Initializing one does not call a function that decides what the members become. Instead the compiler walks the elements in declaration order, bases first and then non-static data members, and copy-initializes each one from the next initializer you supplied. Elements you leave out get their default member initializer if they have one, and are otherwise initialized from an empty brace list, which for scalars means zero.

That is why aggregates are attractive and why the rules are strict. Any feature that would let the class itself take part in initialization, such as a constructor, a virtual function or a private data member, disqualifies the type.

> **Mental model.** An aggregate is a list of named slots. Aggregate initialization fills the slots in order from your list and value-initializes the rest. No function of the class runs to decide anything, so there is nothing for access control or a constructor to enforce.

## What counts as an aggregate, standard by standard

Arrays are always aggregates. For classes the definition has moved in every revision, and code that compiled under one rule changes meaning under the next.

| Standard | What a class aggregate may not have |
| --- | --- |
| C++11 | user-provided constructors, default member initializers, private or protected non-static data members, base classes, virtual functions |
| C++14 | the same, except default member initializers are now allowed |
| C++17 | user-provided, explicit or inherited constructors; private or protected non-static data members; virtual functions; virtual, private or protected bases |
| C++20 | user-declared or inherited constructors; private or protected non-static data members; virtual functions; virtual, private or protected bases |

Several things never stopped a type from being an aggregate: member functions, static data members of any access, a user-declared destructor, and user-declared assignment operators. A lambda's closure type is explicitly not an aggregate. When in doubt, ask the compiler: the C++17 trait `std::is_aggregate_v<T>` reports the answer under whatever language mode you compile with, and a `static_assert` on it protects a type whose users depend on brace initialization.

The C++20 change, from P1008, closed a loophole. Before it, a class with a deleted or private defaulted constructor was still an aggregate, so braces bypassed the constructor entirely.

```cpp
struct NoDefault {
  NoDefault() = delete;
  int x;
};

// NoDefault n{};
// C++17: compiles, aggregate initialization ignores the deleted constructor
// C++20: ill-formed, the type has a user-declared constructor, so {} calls it
```

> **Pitfall.** Adding `S() = default;` to a struct in C++20 silently makes it a non-aggregate. `S{1, 2}` then stops compiling, because there is no constructor taking two arguments. Prefer default member initializers to a defaulted constructor when you want both defaults and aggregate syntax.

## Aggregate initialization and brace elision

Each element is copy-initialized from its initializer, so an explicit constructor of a member type cannot be used to convert it, and since the initializer is a braced list, narrowing is ill-formed. A reference member with no initializer and no default member initializer makes the program ill-formed. For a union, aggregate initialization initializes only the first member, unless a designator names another. Inside any braced list the initializer clauses are evaluated strictly left to right, each one sequenced before the next, which is a stronger guarantee than function arguments get.

```cpp
struct Opts {
  int a;
  int b = 5;
  int c;
};

Opts o{1};   // a is 1, b is 5 from its default member initializer, c is 0
```

When an element is itself an aggregate, its braces can be omitted. Brace elision lets the initializers flow into the subaggregate's elements in order, which is how `int m[2][2] = {1, 2, 3, 4};` and `std::array<int, 3> a = {1, 2, 3};` work: `std::array` is a struct wrapping a built-in array, and the inner braces are elided. Elision is only assumed when an initializer cannot initialize the element directly, and it breaks down when you write some braces but not all of them.

```cpp
#include <array>

struct P { int x, y; };

std::array<P, 2> ok1{{{1, 2}, {3, 4}}};   // all braces written
std::array<P, 2> ok2{P{1, 2}, P{3, 4}};   // each element is a P expression
// std::array<P, 2> bad{{1, 2}, {3, 4}};
// ill-formed: {1, 2} initializes the inner P[2] array, then {3, 4} is
// an extra initializer for a struct with one member
```

## Bases are elements too (C++17)

Since C++17 an aggregate may have public, non-virtual base classes. Each base is an element that comes before the data members, and it is initialized like any other element, with its own braces or through brace elision.

```cpp
struct Base { int b; };
struct Derived : Base { int d; };

Derived x{{1}, 2};   // x.b is 1, x.d is 2
Derived y{1, 2};     // the same, by brace elision
```

Because the base subobject is now initialized directly by aggregate initialization, rather than by `Derived`'s implicit constructor, access checks happen in the context of the code doing the initialization. A base with a protected default constructor used to work and now does not.

```cpp
struct Guarded { protected: Guarded() = default; };
struct Open : Guarded {};

Open a;      // fine: Open's implicit default constructor may call it
// Open b{};
// fine in C++14, where Open was not an aggregate;
// ill-formed since C++17: Guarded() is initialized from {} outside the class
```

## Designated initializers (C++20)

C++20 lets you name the members you initialize: `P p{.x = 1, .y = 2};`. The feature looks like C's, but it is deliberately narrower.

- Designators must appear in declaration order. C allows any order; GCC rejects out-of-order designators and Clang accepts them with a warning.
- Either every initializer clause is designated or none is. You cannot write `{.x = 1, 2}`.
- Only direct non-static data members can be named. There are no nested designators such as `.inner.y`, no array designators such as `[2] = 5`, and no way to name a base class.
- Each member may be designated at most once.

Members you skip are initialized as in ordinary aggregate initialization, from their default member initializer or from `{}`. For a union, a designator selects which member becomes active, and only one may be given.

```cpp
struct Inner { int y; };
struct Outer { int x; Inner in; int z = 7; };
union Num { int i; float f; };

Outer a{.x = 1, .in{2}};    // z is 7
Outer b{.in = {3}};         // x is 0, z is 7
Num n{.f = 1.5f};           // f is the active member
// Outer c{.z = 1, .x = 2}; // ill-formed: out of declaration order
// Outer d{.x = 1, 2};      // ill-formed: mixes designated and positional
```

Designators combined with default member initializers give C++ something close to named arguments. A function taking an options struct by value can be called with only the fields that differ from the defaults, and the names document the call site. Designated lists also take part in overload resolution: [over.ics.list] allows a designated list to convert to a parameter only if that parameter's aggregate type can be initialized from it, so the designator names select the overload.

```cpp
#include <string>

struct Conn { std::string host; int port = 80; int timeout = 30; };
int connect(Conn c) { return c.port + c.timeout; }

struct ByName { int name; };
struct ById   { int id; };
int find(ByName) { return 1; }
int find(ById)   { return 2; }

int a = connect({.host = "db", .timeout = 5});   // port stays 80
int b = find({.id = 7});                         // calls find(ById)
```

> **Standardese.** [dcl.init.aggr] defines the explicitly initialized elements of a designated list as exactly the named members, requires the designators to name members in declaration order, and initializes every other element as if no designator were present. Compilers accept several C forms as extensions; pass `-pedantic` to have them flagged.

## Parenthesized aggregate initialization (C++20)

P0960 made `T(args...)` work for aggregates. When no constructor matches, which for an aggregate means always unless it is a single argument of the same type, the elements are initialized from the parenthesized list. That is what lets `std::make_unique<P>(1, 2)` and `v.emplace_back(1, 2)` construct aggregates, since library code spells construction with parentheses. Arrays work too: `int a[](1, 2, 3);` declares three ints.

The two spellings are not interchangeable. Parentheses do not forbid narrowing, do not perform brace elision, and do not accept designators. Most importantly, a temporary bound to a reference member is not lifetime-extended.

```cpp
struct Ref { const int& r; };

constexpr int braces() { Ref a{42}; return a.r; }
static_assert(braces() == 42);   // the temporary lives as long as a

// constexpr int parens() { Ref b(42); return b.r; }
// static_assert(parens() == 42);
// rejected: the temporary died at the end of the declaration of b,
// so reading b.r is undefined behavior
```

> **Pitfall.** [class.temporary] lists a temporary bound to a reference element of an aggregate initialized from a parenthesized list as an exception to lifetime extension. `Ref b(42);` compiles and leaves `b.r` dangling, while `Ref a{42};` is safe.

## Deduction for aggregate templates (C++20)

Class template argument deduction normally works from constructors and deduction guides, which an aggregate template does not have. In C++17 you had to write a guide by hand, as `std::array` does. C++20 adds an aggregate deduction candidate, synthesized from the element types, so `Pair p{1, 2.0};` deduces `Pair<int, double>`. GCC 16 and Clang 21 also use it for the parenthesized form `Pair p(1, 2.0);`.

```cpp
#include <type_traits>

template <class T, class U>
struct Pair { T first; U second; };

Pair p{1, 2.0};   // C++20: Pair<int, double>, no guide needed
static_assert(std::is_same_v<decltype(p), Pair<int, double>>);
```

The class-template-argument-deduction topic covers how the candidate set is built and how brace elision interacts with it.

## What to remember

- An aggregate is an array or a class whose initialization no constructor controls; its elements are bases, then data members.
- C++14 allowed default member initializers, C++17 allowed public bases, and C++20 banned every user-declared constructor.
- Omitted elements use their default member initializer, otherwise they are initialized from `{}`.
- Brace elision lets inner braces disappear, but `std::array<P, 2>{{1, 2}, {3, 4}}` fails; write all braces or none.
- Since C++17 a base's protected default constructor makes `Derived{}` ill-formed.
- Designators must follow declaration order, cannot be mixed with positional clauses, and cannot nest or index.
- Parenthesized aggregate init allows narrowing and does not extend the lifetime of temporaries bound to reference members.
- C++20 deduces template arguments for aggregate templates without deduction guides.

## Concept Map Outline

- **Aggregates:** Types initialized element by element, with no constructor in charge.
  - **Definition by version:** Arrays always qualify; the class rules changed in every standard since C++11.
    - **C++14:** Default member initializers no longer disqualify a class.
    - **C++17:** Public non-virtual bases allowed; explicit or inherited constructors disqualify.
    - **C++20:** Any user-declared constructor, even = default or = delete, disqualifies.
    - **Never disqualifying:** Member functions, statics, a user-declared destructor and assignment operators.
  - **Aggregate initialization:** Elements, bases first, are copy-initialized in order from the list.
    - **Omitted elements:** Use the default member initializer, otherwise are initialized from {}.
    - **No narrowing:** Braced aggregate initialization rejects narrowing conversions.
    - **Unions:** Without a designator only the first member is initialized.
    - **Brace elision:** Inner braces may be dropped; {{1,2},{3,4}} fails for std::array<P,2>.
  - **Base classes (C++17):** Each public base is an element initialized before the data members.
    - **Derived{{1}, 2}:** The base gets its own braces, or brace elision fills it.
    - **Protected base ctor:** Derived{} is ill-formed since C++17: the base is initialized from outside.
  - **Designated (C++20):** Name members with .x = value, a deliberately narrow subset of C.
    - **Declaration order:** Designators must follow member order, unlike C.
    - **All or none:** Designated and positional clauses cannot be mixed.
    - **No nesting or indices:** No .a.b, no [2] = x, and bases cannot be named.
    - **Union member choice:** A single designator picks the union's active member.
  - **Parentheses (C++20):** T(args...) aggregate-initializes when no constructor is viable.
    - **Library construction:** make_unique<P>(1, 2) and emplace_back(1, 2) now work for aggregates.
    - **Narrowing allowed:** N n(2.5) compiles and truncates, while N n{2.5} is ill-formed.
    - **No lifetime extension:** A temporary bound to a reference member dies at the end of the declaration.
  - **CTAD for aggregates:** C++20 synthesizes a deduction candidate from the element types.
    - **No guide needed:** Pair p{1, 2.0} deduces Pair<int, double> without a deduction guide.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.init.aggr], [dcl.init.list])

In C++20, is the declaration of `n` well-formed?

```cpp
struct NoDefault {
  NoDefault() = delete;
  int x;
};

int main() {
  NoDefault n{};
  (void)n;
}
```

A. Yes: `NoDefault` is an aggregate, so `{}` never calls the constructor
B. Yes: `n.x` is zero-initialized
C. No: the type is not an aggregate, so `{}` calls the deleted default constructor
D. Yes in C++20, but it was ill-formed in C++17

**Answer (C):** No: the type is not an aggregate, so `{}` calls the deleted default constructor

**Why:** Since C++20 (P1008) a class with any user-declared constructor is not an aggregate, and a deleted constructor is user-declared. Empty braces on a class with a default constructor value-initialize, which selects the deleted constructor, so the program is ill-formed. The first option was true in C++11 through C++17, where only user-provided constructors disqualified a type, so the code compiled; the last option has the history backwards.

### Question 2 [warmup] ([dcl.init.aggr], [dcl.init.general])

In C++20, is this declaration well-formed?

```cpp
struct P { int x, y; };

P p{.y = 1, .x = 2};
```

A. No: designators must appear in declaration order
B. Yes: `p.x` is 2 and `p.y` is 1, as in C
C. Yes: the values are applied positionally, so `p.x` is 1
D. Yes, but the order in which `x` and `y` are initialized is unspecified

**Answer (A):** No: designators must appear in declaration order

**Why:** C++20 designated initializers must name members in the order they are declared, so this is ill-formed. C accepts any order, which makes the second option tempting, and Clang accepts it as an extension with a `-Wreorder-init-list` warning; GCC rejects it. The rule exists so that initializers are evaluated in the same order as members are initialized.

### Question 3 [warmup] ([dcl.init.aggr])

What does this program print?

```cpp
#include <cstdio>

struct Opts {
  int a;
  int b = 5;
  int c;
};

int main() {
  Opts o{1};
  std::printf("%d %d %d\n", o.a, o.b, o.c);
}
```

A. `1 0 0`
B. Nothing useful: `o.c` is indeterminate, so the behavior is undefined
C. It does not compile: `c` needs an initializer
D. `1 5 0`

**Answer (D):** `1 5 0`

**Why:** `Opts` is an aggregate (default member initializers are allowed since C++14). Elements without an initializer use their default member initializer, so `b` is 5, and otherwise are copy-initialized from an empty initializer list, which zeroes `c`. The indeterminate answer would be right for `Opts o;`, which default-initializes, but any brace list makes every element initialized.

### Question 4 [tricky] ([dcl.init.aggr], [array.overview])

Is the declaration of `a` well-formed?

```cpp
#include <array>

struct P { int x, y; };

std::array<P, 2> a{{1, 2}, {3, 4}};
```

A. Yes: it creates `P{1, 2}` and `P{3, 4}`
B. No: `{1, 2}` initializes the inner array, so `{3, 4}` is an excess initializer
C. Yes, but `a[1]` is value-initialized and `{3, 4}` is ignored
D. No: `std::array` cannot be initialized from nested braces

**Answer (B):** No: `{1, 2}` initializes the inner array, so `{3, 4}` is an excess initializer

**Why:** `std::array<P, 2>` is a struct whose single element is a built-in `P[2]`. The first clause `{1, 2}` is a braced list, so it initializes that inner array, as `P[2]{1, 2}`, filling `a[0]`. The second clause has no element left to initialize, so the program is ill-formed. Brace elision only helps when you elide all the inner braces, `{1, 2, 3, 4}`, or write all of them, `{{{1, 2}, {3, 4}}}`.

### Question 5 [tricky] ([class.temporary], [dcl.init.general])

In C++20, what does the standard say about this program?

```cpp
struct Ref { const int& r; };

int main() {
  Ref a{42};
  Ref b(42);
  return a.r + b.r;
}
```

A. It returns 84
B. It is ill-formed: an aggregate with a reference member cannot be initialized with parentheses
C. The behavior is undefined: `b.r` refers to a temporary that has been destroyed
D. The behavior is undefined: both `a.r` and `b.r` dangle

**Answer (C):** The behavior is undefined: `b.r` refers to a temporary that has been destroyed

**Why:** Both declarations are aggregate initialization; the parenthesized form is valid since C++20. With braces, the temporary bound to the reference member is lifetime-extended to the lifetime of `a`. [class.temporary] makes an exception for an aggregate initialized from a parenthesized expression-list, so the temporary behind `b.r` dies at the end of that declaration and reading it is undefined behavior. That asymmetry is why the first option is so tempting.

### Question 6 [tricky] ([dcl.init.aggr], [class.protected])

In C++20, is the declaration of `b` well-formed?

```cpp
struct Guarded { protected: Guarded() = default; };
struct Open : Guarded {};

int main() {
  Open b{};
  (void)b;
}
```

A. No: `Open` is an aggregate, and `Guarded()` is not accessible where the base is initialized
B. Yes: `Open`'s implicit default constructor calls `Guarded()`
C. Yes: a derived class may always call a protected base constructor
D. It is implementation-defined

**Answer (A):** No: `Open` is an aggregate, and `Guarded()` is not accessible where the base is initialized

**Why:** Since C++17 a class with a public base can be an aggregate, so `Open{}` is aggregate initialization and the base element is copy-initialized from `{}` in the context of `main`, where the protected constructor is inaccessible. The program is ill-formed. Before C++17 `Open` was not an aggregate and its implicit constructor called `Guarded()` from inside the derived class, which is what the second option describes; `Open b;` still works that way.

### Question 7 [standardese] ([dcl.init.aggr], [expr.prim.lambda.closure])

Which of these is an aggregate in C++20?

A. `struct A { private: int x; };`
B. `struct B { B() = default; int x; };`
C. The closure type of `[] {}`
D. `struct D : Base { int d; void f(); ~D(); };` where `Base` is a class with only public members

**Answer (D):** `struct D : Base { int d; void f(); ~D(); };` where `Base` is a class with only public members

**Why:** Member functions and a user-declared destructor never disqualify a class, and since C++17 a public non-virtual base is allowed, so `D` is an aggregate. A private non-static data member disqualifies `A`. `B` has a user-declared constructor, which disqualifies it since C++20 even though it is defaulted, the tempting answer for anyone who learned the C++17 rule. The standard states outright that a closure type is not an aggregate.

### Question 8 [standardese] ([over.match.class.deduct])

In C++20, with no deduction guides declared, what is `decltype(p)`?

```cpp
template <class T, class U>
struct Pair { T first; U second; };

Pair p{1, 2.0};
```

A. The declaration is ill-formed: there is no constructor or guide to deduce from
B. `Pair<int, double>`
C. `Pair<double, double>`
D. `Pair<int, int>`

**Answer (B):** `Pair<int, double>`

**Why:** C++20 adds an aggregate deduction candidate: for an aggregate class template, the compiler synthesizes a candidate whose parameters are the element types, so `T` deduces from `1` and `U` from `2.0`. In C++17 deduction failed here unless you wrote a guide, which is the first option and the reason `std::array` ships with one.

# Type Deduction: auto, decltype, and CTAD

> Master template-style auto deduction, the braced-initializer exception, decltype's two-rule split, structured bindings, and Class Template Argument Deduction.

- **Source:** C++ Atlas (https://cppatlas.com/topics/type-deduction-auto-decltype)
- **Track:** Types and initialization
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [dcl.type.auto.deduct] (https://eel.is/c++draft/dcl.type.auto.deduct), [dcl.type.decltype] (https://eel.is/c++draft/dcl.type.decltype), [temp.deduct.type] (https://eel.is/c++draft/temp.deduct.type), [dcl.struct.bind] (https://eel.is/c++draft/dcl.struct.bind), [over.match.class.deduct] (https://eel.is/c++draft/over.match.class.deduct)
- **cppreference links:** [Placeholder type specifiers](https://en.cppreference.com/w/cpp/language/auto), [decltype specifier](https://en.cppreference.com/w/cpp/language/decltype), [Template argument deduction](https://en.cppreference.com/w/cpp/language/template_argument_deduction), [Structured binding declaration](https://en.cppreference.com/w/cpp/language/structured_binding), [Class template argument deduction](https://en.cppreference.com/w/cpp/language/class_template_argument_deduction)
- **Prerequisites:** initialization-forms

C++ offers several ways to omit spelling a type—`auto`, `decltype`, `decltype(auto)`, structured bindings, and Class Template Argument Deduction (CTAD)—yet they obey different rulebooks. Treating `auto` and `decltype` as interchangeable causes dangling references, unintended copies, and surprise `std::initializer_list` deductions.

## auto is template argument deduction in disguise

Under `[dcl.type.auto.deduct]`, deducing `auto` in `ParamSpec x = expr;` is mechanically identical to inventing a helper function template `template<class T> void f(ParamSpec_T param);` and calling `f(expr);`. Whatever `T` template argument deduction solves for replaces `auto`.

That single equivalence explains all three `auto` specifier patterns:

1. **`auto x = expr;` (by value):** Strips references first, then drops top-level `const` and `volatile`, and decays array or function expressions to pointers.
2. **`const auto& x = expr;` or `auto* p = ptr;` (reference or pointer):** Drops top-level reference from `expr`, yet *preserves* inner `const`/`volatile` qualifiers and prevents array-to-pointer decay.
3. **`auto&& x = expr;` (forwarding reference):** If `expr` is an lvalue of type `U`, reference collapsing deduces `auto` as `U&` so `x` has type `U&`; if `expr` is an rvalue of type `U`, `x` has type `U&&`.

| Initializer `expr` (given `const int ci = 7; int arr[3]{};`) | `auto x = expr` | `const auto& x = expr` | `auto&& x = expr` | `decltype((expr))` |
| --- | --- | --- | --- | --- |
| `ci` (lvalue `const int`) | `int` | `const int&` | `const int&` | `const int&` |
| `42` (prvalue `int`) | `int` | `const int&` | `int&&` | `int` |
| `arr` (lvalue `int[3]`) | `int*` | `const int (&)[3]` | `int (&)[3]` | `int (&)[3]` |
| `std::move(ci)` (xvalue `const int`) | `int` | `const int&` | `const int&&` | `const int&&` |

> **Mental model.** `auto` behaves like a value parameter unless decorated with `&`, `*`, or `&&`—it strips references and top-level `const` by default, whereas `decltype` acts as an exact mirror of the expression's type and value category.

```cpp
#include <type_traits>

void check_auto_deduction() {
    const int ci = 7;
    const int& ref = ci;

    auto a = ref;        // int (drops & and top-level const)
    const auto& b = ref; // const int& (preserves constness)
    auto&& c = ci;       // const int& (forwarding ref binds lvalue)
    auto&& d = 7;        // int&& (forwarding ref binds rvalue)

    int arr[3]{};
    auto ptr = arr;      // int* (by-value auto decays array)
    auto& arr_ref = arr; // int (&)[3] (reference avoids decay)

    static_assert(std::is_same_v<decltype(a), int>);
    static_assert(std::is_same_v<decltype(b), const int&>);
    static_assert(std::is_same_v<decltype(c), const int&>);
    static_assert(std::is_same_v<decltype(d), int&&>);
    static_assert(std::is_same_v<decltype(ptr), int*>);
    static_assert(std::is_same_v<decltype(arr_ref), int(&)[3]>);
}
```

## The braced-initializer exception

`auto` differs from template argument deduction in exactly **one** place: braced initializers (`{...}`). A function template `template<class T> void f(T);` cannot deduce `T` from `f({1, 2});` because a braced-init-list has no type of its own (`[temp.deduct.type]`). By contrast, `auto` has special rules refined in C++17:

- **Copy-list-initialization (`auto x = {1, 2};`):** Deduces `std::initializer_list<int>`, provided every element deduces the same type.
- **Direct-list-initialization (`auto x{1};`):** Deduces `int` since C++17 (single element only; `auto x{1, 2};` is ill-formed).

> **Pitfall.** Writing `auto x = {42};` creates a `std::initializer_list<int>`, not an `int`! Use `auto x = 42;` or `auto x{42};` when you want `int`.

## decltype and decltype(auto)

Unlike `auto`, `decltype(e)` (`[dcl.type.decltype]`) never strips `const` or references and never evaluates `e`. Its rules split sharply into two branches:

1. **Unparenthesized id-expression or class member access** (`decltype(x)`, `decltype(obj.field)`): Yields the **declared type** of that variable or data member.
2. **Any other expression** (`decltype((x))`, `decltype(x + 1)`, `decltype(fn())`): Classifies the expression by value category—yielding **`T&` for lvalue**, **`T&&` for xvalue**, and **`T` for prvalue**.

> **Standardese.** Under `[dcl.type.decltype]`, wrapping a variable name in extra parentheses transforms an unparenthesized id-expression into a parenthesized lvalue expression, turning `decltype(x)` (`int`) into `decltype((x))` (`int&`).

C++14 added **`decltype(auto)`** so forwarding wrappers and return types can apply `decltype` rules to an initializer or `return` operand without repeating the expression inside `decltype(...)`. Remember that `decltype(auto)` cannot be adorned with `*` or `&`—it stands alone as the full type specifier.

```cpp
#include <type_traits>
#include <utility>

template<class Fn, class... Args>
decltype(auto) relay_call(Fn&& fn, Args&&... args) {
    return std::forward<Fn>(fn)(std::forward<Args>(args)...); // Preserves int&, int&&, or int
}

int& get_first(int* arr) { return arr[0]; }

void check_decltype() {
    int x = 5;
    static_assert(std::is_same_v<decltype(x), int>);
    static_assert(std::is_same_v<decltype((x)), int&>);

    int nums[2]{10, 20};
    decltype(auto) r = relay_call(get_first, nums);
    static_assert(std::is_same_v<decltype(r), int&>);
    r = 99; // Mutates nums[0] directly
}
```

> **Pitfall.** Writing `decltype(auto) make() { int local = 42; return (local); }` compiles silently with a catastrophic dangling reference! Because `(local)` is a parenthesized lvalue expression, `decltype(auto)` deduces `int&` rather than `int` and returns a reference to destroyed stack storage.

## Structured bindings under the hood

Structured bindings (`auto [a, b] = expr;`, `[dcl.struct.bind]`) appear to declare two independent variables `a` and `b`. In reality, the compiler introduces a single hidden variable `e` whose type is deduced from the qualifiers written on `auto` (`auto e = expr;`, `const auto& e = expr;`, or `auto&& e = expr;`). The identifiers `a` and `b` are **bindings (aliases)** into `e` via one of three protocols: array elements, `std::tuple_size` + `get`, or public non-static data members.

A subtle consequence follows: `decltype(a)` queries the **declared member or `std::tuple_element` type**, *not* the reference-ness of `auto& [a, b]`! Even when `auto& [a, b] = pair;` mutates `pair` in place, `decltype(a)` is `int`, whereas `decltype((a))` is `int&`. Also note that C++20 fixed a C++17 limitation: structured bindings can now be captured directly by lambdas (`[a]`), since C++20 no longer treats bindings as un-capturable non-variables.

```cpp
#include <type_traits>

struct Entry {
    int id;
    double score;
};

void check_bindings() {
    Entry e{1, 9.5};
    auto& [id_ref, score_ref] = e;
    id_ref = 2; // Mutates e.id directly

    // decltype(id_ref) reflects Entry::id's declared type (int), NOT int&!
    static_assert(std::is_same_v<decltype(id_ref), int>);
    static_assert(std::is_same_v<decltype((id_ref)), int&>);
}
```

## Class Template Argument Deduction and guides

Before C++17, constructing `std::pair` or `std::lock_guard` required repeating template arguments or calling `std::make_pair`. **Class Template Argument Deduction (CTAD)** (`[over.match.class.deduct]`) allows `std::pair p(1, 2.5);` by synthesizing imaginary function templates called **deduction guides** from every constructor of the class template—plus allowing explicit user-defined guides (`Box(const char*) -> Box<std::string>;`).

Two rules keep CTAD predictable in practice:

- **All-or-nothing deduction:** Until you write `std::pair<int, double>`, CTAD only runs when *zero* template arguments are supplied (never `std::pair<int>(1, 2.5)`).
- **Copy-deduction candidate priority:** Writing `std::vector v2{v1};` (where `v1` is already `std::vector<int>`) deduces `std::vector<int>`, not `std::vector<std::vector<int>>`, because CTAD gives the synthesized copy-constructor guide priority for single-argument matching specialization types. Adding a second element (`std::vector v3{v1, v1};`) falls back to `initializer_list` and produces `std::vector<std::vector<int>>`.

In C++20, CTAD also gained automatic deduction for **aggregates** and **alias templates**, eliminating the need for boilerplate deduction guides on simple wrapper structs.

```cpp
#include <string>
#include <type_traits>
#include <vector>

template<class T>
struct Box {
    T value;
};
// User-defined deduction guide transforms C-string literals into std::string boxes.
Box(const char*) -> Box<std::string>;

void check_ctad() {
    std::vector v1{1, 2, 3};     // std::vector<int>
    std::vector v2{v1};          // Copy-deduction candidate -> std::vector<int>
    std::vector v3{v1, v1};      // Two elements -> std::vector<std::vector<int>>

    Box bx{"hello"};             // Deduction guide -> Box<std::string>
    static_assert(std::is_same_v<decltype(v2), std::vector<int>>);
    static_assert(std::is_same_v<decltype(v3), std::vector<std::vector<int>>>);
    static_assert(std::is_same_v<decltype(bx), Box<std::string>>);
}
```

## What to remember

- By-value `auto` mirrors template value deduction: it strips references and top-level `const`/`volatile` and decays arrays/functions to pointers.
- `auto x = {1};` deduces `std::initializer_list<int>`, whereas C++17 `auto x{1};` deduces `int` and `auto x{1, 2};` is ill-formed.
- `decltype(name)` returns the declared type; `decltype((name))` (or any compound expression) adds `&` for lvalues and `&&` for xvalues.
- Never `return (local);` from a `decltype(auto)` function—the extra parentheses deduce a dangling reference.
- In `auto& [a, b] = s;`, `decltype(a)` is the element's declared type while `decltype((a))` reflects the reference binding; CTAD's copy-deduction candidate makes `std::vector{v1}` copy rather than nest.

## Concept Map Outline

- **Type Deduction & CTAD:** Explains how auto, decltype, structured bindings, and CTAD infer types without spelling them explicitly.
  - **Auto Deduction:** Applies function-template argument deduction rules to variable and return placeholders.
    - **By-Value auto:** Strips references and top-level cv-qualifiers and decays arrays or functions to pointers.
    - **const auto& & auto*:** Preserves pointee constness and stops array-to-pointer decay.
    - **Forwarding auto&&:** Collapses to lvalue reference for lvalues and rvalue reference for rvalues.
  - **Braced Initializer Rule:** Special auto deduction divergence from standard template argument deduction.
    - **Copy-List auto = {...}:** Copy-list syntax deduces std::initializer_list<T> when elements share a type.
    - **auto x{val} (C++17):** Direct-list syntax deduces single element type T and rejects multi-element lists.
  - **Decltype Rules:** Inspects declared entity types or expression value categories without evaluating operands.
    - **Unparenthesized Id-Expression:** decltype(x) and decltype(obj.m) yield the exact declared type of that entity.
    - **Parenthesized & Value Category:** Other expressions yield T& for lvalue, T&& for xvalue, and T for prvalue.
    - **decltype(auto):** Forwards return references exactly, though return (local); causes dangling reference UB.
  - **Structured Bindings:** Introduces a hidden deduced variable with named aliases into array, tuple, or struct fields.
    - **Hidden Variable Qualifiers:** Qualifiers on auto apply to the hidden whole-object variable, not individual bindings.
    - **decltype on Bindings:** decltype(binding) yields the member or tuple_element type rather than a reference.
  - **CTAD & Guides:** Deduces class template arguments from constructors, user guides, aggregates, and aliases.
    - **User Deduction Guides:** Explicit Pattern -> Template<T> rules override or extend constructor synthesis.
    - **Copy-Deduction Candidate:** Preferentially deduces std::vector{v1} as copying v1 rather than nesting vectors.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.type.auto.deduct], [temp.deduct.type])

Given `const int ci = 7; const int& r = ci; auto x = r;`, what is the deduced type of `x`?

A. const int&
B. const int
C. int
D. int&

**Answer (C):** int

**Why:** By-value `auto` follows template parameter deduction (`template<class T> void f(T)`), which strips references first and then discards top-level cv-qualifiers. Therefore `x` is a plain mutable `int`.

### Question 2 [warmup] ([dcl.type.auto.deduct])

What are the deduced types of `a` and `b` in C++17 and later?

```cpp
auto a{10};
auto b = {10};
```

A. Both `a` and `b` are `std::initializer_list<int>`.
B. `a` is `int`; `b` is `std::initializer_list<int>`.
C. Both `a` and `b` are `int`.
D. `a` is ill-formed; `b` is `int`.

**Answer (B):** `a` is `int`; `b` is `std::initializer_list<int>`.

**Why:** Since C++17 (N3922), direct-list-initialization `auto a{10};` with a single element deduces `int`, whereas copy-list-initialization `auto b = {10};` continues to deduce `std::initializer_list<int>`.

### Question 3 [tricky] ([dcl.type.decltype], [dcl.type.auto.deduct])

What happens when calling `auto& r = bad_return();` on this C++23 function?

```cpp
decltype(auto) bad_return() {
    int local = 42;
    return (local);
}
```

A. It returns a dangling reference (`int&`) to destroyed stack variable `local`.
B. It returns `int` by value cleanly.
C. It triggers guaranteed copy elision into the caller's object.
D. It fails to compile because parentheses around a return operand are forbidden.

**Answer (A):** It returns a dangling reference (`int&`) to destroyed stack variable `local`.

**Why:** With `decltype(auto)`, `return (local);` applies `decltype((local))`. Because `(local)` is a parenthesized lvalue expression rather than an unparenthesized id-expression, `decltype` yields `int&`, returning a dangling reference to `local`.

### Question 4 [tricky] ([over.match.class.deduct])

Given `std::vector v1{1, 2, 3};`, what are the types of `v2` and `v3` deduced by CTAD?

```cpp
std::vector v1{1, 2, 3};
std::vector v2{v1};
std::vector v3{v1, v1};
```

A. Both `v2` and `v3` are `std::vector<std::vector<int>>`.
B. `v2` is `std::vector<std::vector<int>>`; `v3` is ill-formed.
C. Both `v2` and `v3` are `std::vector<int>`.
D. `v2` is `std::vector<int>`; `v3` is `std::vector<std::vector<int>>`.

**Answer (D):** `v2` is `std::vector<int>`; `v3` is `std::vector<std::vector<int>>`.

**Why:** Under [over.match.class.deduct], single-element `std::vector v2{v1}` selects the synthesized copy-deduction candidate, producing `std::vector<int>` as a copy of `v1`. Passing two `v1` arguments in `v3{v1, v1}` cannot match the copy constructor and instead matches `initializer_list<std::vector<int>>`.

### Question 5 [standardese] ([dcl.struct.bind], [dcl.type.decltype])

Given `struct S { int x; double y; }; S s{1, 2.0}; auto& [a, b] = s;`, what are `decltype(a)` and `decltype((a))`?

```cpp
struct S { int x; double y; };
S s{1, 2.0};
auto& [a, b] = s;
```

A. `decltype(a)` is `int&`; `decltype((a))` is `int&`.
B. `decltype(a)` is `int`; `decltype((a))` is `int`.
C. `decltype(a)` is `int`; `decltype((a))` is `int&`.
D. `decltype(a)` is `int&&`; `decltype((a))` is `int&`.

**Answer (C):** `decltype(a)` is `int`; `decltype((a))` is `int&`.

**Why:** Under [dcl.type.decltype] and [dcl.struct.bind], `a` is a structured binding rather than a reference variable, so `decltype(a)` yields the referenced member's declared type (`int`). Parenthesizing `(a)` turns it into a general lvalue expression, so `decltype((a))` yields `int&`.

### Question 6 [standardese] ([dcl.type.auto.deduct], [temp.deduct.call])

Given `int arr[4]{};`, why do `auto p = arr;` and `auto& r = arr;` deduce different types?

A. Because `auto` without `&` performs array-to-pointer decay (`int*`), whereas `auto&` binds to the actual array type (`int(&)[4]`).
B. Because `auto&` converts `arr` to `std::span<int, 4>`.
C. Because `auto p = arr;` is ill-formed in C++20 unless `arr` is `std::array`.
D. Because `auto& r = arr;` decays `arr` into a reference to pointer `int*&`.

**Answer (A):** Because `auto` without `&` performs array-to-pointer decay (`int*`), whereas `auto&` binds to the actual array type (`int(&)[4]`).

**Why:** By-value template parameter deduction (`template<class T> void f(T)`) applies lvalue-to-rvalue and array-to-pointer decay before deducing `T`, so `auto p = arr;` deduces `int*`. Reference parameter deduction (`template<class T> void g(T&)`) suppresses array decay, so `auto& r = arr;` deduces `int(&)[4]`.

# Enumerations and unions

> An enumeration is an integer type with named values and a precisely defined set of valid values; a union is storage for one of several objects at a time. Both are easy to misuse, because the language lets you hold values and read members it has not promised you.

- **Source:** C++ Atlas (https://cppatlas.com/topics/enumerations-and-unions)
- **Track:** Types and initialization
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [dcl.enum] (https://eel.is/c++draft/dcl.enum), [enum.udecl] (https://eel.is/c++draft/enum.udecl), [expr.static.cast] (https://eel.is/c++draft/expr.static.cast), [dcl.init.list] (https://eel.is/c++draft/dcl.init.list), [utility.underlying] (https://eel.is/c++draft/utility.underlying), [class.union] (https://eel.is/c++draft/class.union), [class.union.anon] (https://eel.is/c++draft/class.union.anon), [class.mem.general] (https://eel.is/c++draft/class.mem.general)
- **cppreference links:** [Enumeration declaration](https://en.cppreference.com/w/cpp/language/enum), [std::to_underlying](https://en.cppreference.com/w/cpp/utility/to_underlying), [std::underlying_type](https://en.cppreference.com/w/cpp/types/underlying_type), [Union declaration](https://en.cppreference.com/w/cpp/language/union), [std::variant](https://en.cppreference.com/w/cpp/utility/variant)
- **Prerequisites:** fundamental-types-and-arithmetic-conversions, initialization-forms, object-lifetime-and-storage

## The one idea

An enumeration is a distinct type whose representation is an integer type, called its **underlying type**. Its enumerators are named constants, but its set of valid values is usually larger than the enumerators and sometimes smaller than the underlying type. Converting a value outside that set is not a wrap-around; since C++17 it is undefined behavior.

A union is a class whose non-static data members all share the same storage, so at most one of them is alive at any moment. That member is the **active member**. The language does not track which one it is; you must. Reading any other member reads an object whose lifetime has not begun, which is undefined behavior, with one carefully bounded exception.

> **Mental model.** An enum is an integer with a fence around its legal values, and a union is a box that holds one object at a time. Neither checks at run time, so both are only as safe as the code that remembers what is inside.

## Scoped and unscoped enumerations

An unscoped enumeration, `enum Color { red, green };`, puts its enumerators into the enclosing scope, and its values convert implicitly to integers through integral promotion. A scoped enumeration, `enum class Color { red, green };`, keeps its enumerators inside its own scope, so you must write `Color::red`, and it never converts implicitly to anything. The conversion requires a `static_cast` or `std::to_underlying`.

```cpp
enum Fruit { apple, pear };
enum class Color { red, green };

int a = pear + 1;                       // fine: Fruit promotes to int
// int b = Color::green;                // ill-formed: no implicit conversion
int c = static_cast<int>(Color::green); // fine: explicit
```

The **underlying type** of a scoped enumeration is `int` unless you name another with `enum class E : std::uint8_t`. For an unscoped enumeration you may also fix it with `: type`. If you do not, the underlying type is an implementation-defined integral type able to represent every enumerator, and it is not larger than `int` unless some enumerator needs it. `std::underlying_type_t<E>` names it, and C++23 adds `std::to_underlying(e)` in `<utility>` as shorthand for `static_cast<std::underlying_type_t<E>>(e)`.

Implicit conversions of unscoped enumerations are also being narrowed. C++20 deprecated arithmetic between two different enumeration types and between an enumeration and a floating-point type. C++26 (P2864) removes those conversions; GCC 16 reports them with a warning.

## The range of values, and what is undefined

Which integers is an enumeration allowed to hold? [dcl.enum] gives two answers.

- With a **fixed underlying type**, which every scoped enumeration has, the values are exactly the values of the underlying type. `enum class Id : std::uint32_t {}` has no enumerators, yet every `uint32_t` is a valid `Id`.
- Without one, the values are those of the smallest bit-field that can hold every enumerator. For `enum Small { a = 1, b = 4 };` that is three unsigned bits, so the valid values are 0 through 7. If an enumerator is negative, the range is the corresponding two's complement range.

Converting an integer to an enumeration with `static_cast` gives the corresponding value when it is in range. For a fixed underlying type, the integer is first converted to that type, which is ordinary integral conversion and always defined. For an enumeration without a fixed type, an out-of-range value gave an unspecified result before C++17. Since C++17, through CWG 1766, the behavior is undefined.

```cpp
enum Small { a = 1, b = 4 };     // values 0 to 7

constexpr Small ok = static_cast<Small>(7);  // fine: in range, no enumerator needed
// constexpr Small bad = static_cast<Small>(8);
// undefined behavior; Clang rejects it as not a constant expression,
// GCC 16 accepts it
```

> **Standardese.** [expr.static.cast] says that if the enumeration type does not have a fixed underlying type and the value is outside its range of values, the behavior is undefined. The range is defined in [dcl.enum] as the values of the smallest bit-field that can store all the enumerators. Optimizers may assume an enum variable only holds such values; GCC exposes this as `-fstrict-enums`.

## Initializing enums from integers and `using enum`

Before C++17 the only way to make an `Id` from a number was a cast. P0138, in C++17, allows direct-list-initialization of an enumeration with a fixed underlying type from a single integer, without a cast. It is deliberately narrow: only braces without `=`, and narrowing is still forbidden.

```cpp
#include <cstdint>

enum class Id : std::uint32_t {};
enum class Byte : unsigned char {};

Id i{42};          // fine since C++17
// Id j = {42};    // ill-formed: copy-list-initialization
// Id k(42);       // ill-formed: parentheses do not get the new rule
// Id m = 42;      // ill-formed: no implicit conversion
// Byte n{300};    // ill-formed: 300 narrows to unsigned char
```

This is how `std::byte` is meant to be created: `std::byte b{0x2a};`.

C++20's `using enum` (P1099) brings all of a scoped enumeration's enumerators into the current scope. It works at namespace, class and block scope, and it removes the repetition from a `switch`.

```cpp
enum class Color { red, green };

int code(Color c) {
  switch (c) {
    using enum Color;
    case red:   return 1;   // Color::red
    case green: return 2;
  }
  return 0;
}
```

## Unions: one active member

Each non-static data member of a union is allocated as if it were the only member of a struct, so all of them start at the union's address, and the union is large enough for its largest member. A union may have member functions, including constructors and destructors, but no virtual functions, no base classes, and no reference members, and it may not be used as a base class.

Initialization makes a member active: aggregate initialization activates the first member, and a C++20 designator chooses another, as in `U u{.f = 1.5f};`. Assignment through the built-in or a trivial assignment operator starts the lifetime of the assigned member and ends the old one's. For a member with non-trivial construction you must end the old member's lifetime and construct the new one explicitly, with placement `new` or `std::construct_at`.

Reading an inactive member is undefined behavior, because it accesses an object that is not within its lifetime. Constant evaluation is required to reject core-language undefined behavior, which makes this easy to see.

```cpp
union U { int i; float f; };

constexpr float reinterpret() {
  U u{.i = 1};
  return u.f;    // reads the inactive member
}
// constexpr float x = reinterpret();
// ill-formed: not a constant expression, because u.f is not active
```

> **Pitfall.** Type punning through a union is valid C, and GCC documents it as supported, but it is undefined behavior in standard C++. To reinterpret bytes, use `std::bit_cast` (C++20) or `std::memcpy`; the strict-aliasing-and-undefined-behavior topic covers why.

### The common initial sequence

The one exception concerns structs that start the same way. If a standard-layout union holds several standard-layout structs, and the active one shares a **common initial sequence** with another, you may read a member of that common prefix through either struct. The common initial sequence is the longest run of leading members that correspond pairwise: layout-compatible types and matching bit-field widths, among a few other conditions. This is what makes the classic tagged-message layout work.

```cpp
#include <cstdio>

struct Circle { int tag; double radius; };
struct Rect   { int tag; long width; };
union Shape   { Circle c; Rect r; };

int main() {
  Shape s{.c = {1, 2.0}};
  std::printf("%d\n", s.r.tag);   // fine: tag is in the common initial sequence
  // s.r.width would be undefined: it is not part of the common prefix
}
```

## Anonymous unions and non-trivial members

An anonymous union, `union { int i; float f; };`, declares an unnamed object whose members are injected into the enclosing scope. It may have only public non-static data members: no member functions and no static members. In the global namespace or a named namespace it must be declared `static`. Placed inside a struct next to a tag, it is the usual hand-written tagged union, and the enclosing struct is called a union-like class.

Since C++11 a union may have members with non-trivial special member functions, such as `std::string`. The price is that the union's corresponding special member functions become deleted. Its default constructor is deleted unless some variant member has a default member initializer, and at most one may have one. Its destructor is deleted if a member has a non-trivial destructor, so you must write one, and since the union cannot know which member is active, that destructor usually does nothing and the owner destroys the active member by hand. These are the C++23 rules; C++26 relaxes some of them for unions through P3074, which GCC 16 does not yet implement.

```cpp
#include <memory>
#include <string>

union Slot {
  int i;
  std::string s;
  Slot() : i(0) {}   // required: the implicit default constructor is deleted
  ~Slot() {}         // required: the implicit destructor is deleted
};

void demo() {
  Slot slot;                          // i is active
  std::construct_at(&slot.s, "hi");   // now s is active
  std::destroy_at(&slot.s);           // end s before slot goes away
}
```

`std::variant` packages all of this safely. It stores the discriminator alongside the storage, constructs and destroys the active alternative for you, and turns a wrong-type access through `std::get` into a `std::bad_variant_access` exception rather than undefined behavior. Prefer it whenever you would otherwise write a tag and an anonymous union by hand; the optional-variant-any topic covers it in depth.

## What to remember

- Scoped enums have scoped names, no implicit conversions and a fixed underlying type, `int` by default.
- An enum with a fixed underlying type accepts every value of that type; one without accepts the values of the smallest bit-field holding its enumerators.
- Casting an out-of-range value to an enum without a fixed type is undefined since C++17 and gave an unspecified value before.
- Since C++17, `Id i{42};` initializes an enum with a fixed underlying type; `= {42}`, `(42)` and narrowing values do not.
- `using enum E;` (C++20) brings the enumerators into scope; `std::to_underlying` (C++23) converts back.
- A union has at most one active member, and reading another one is undefined behavior, except for the common initial sequence of standard-layout structs.
- Non-trivial union members delete the union's special members; construct and destroy the active member yourself.
- Use `std::bit_cast` for reinterpreting bytes and `std::variant` for a safe tagged union.

## Concept Map Outline

- **Enumerations and unions:** Enums are integers with fenced values; unions hold one live member at a time.
  - **Scoped vs unscoped:** enum class scopes its names and never converts implicitly.
    - **Unscoped promotes:** Unscoped enumerators leak into the enclosing scope and promote to int.
    - **Underlying type:** Scoped defaults to int; unscoped without : T uses an implementation-defined type.
    - **std::to_underlying:** C++23 shorthand for static_cast to std::underlying_type_t<E>.
    - **Deprecated arithmetic:** Enum-enum and enum-float arithmetic deprecated in C++20, removed in C++26.
  - **Range of values:** The set of values an enum may hold, defined in [dcl.enum].
    - **Fixed underlying type:** Every value of the underlying type is valid, enumerator or not.
    - **No fixed type:** Values of the smallest bit-field holding all enumerators, e.g. 0 to 7.
    - **Out-of-range cast:** Undefined since C++17 (CWG 1766); an unspecified value before.
  - **Enum initialization:** Ways to make an enum value without a cast.
    - **Id i{42} (C++17):** Direct-list-init from an integer works only with a fixed underlying type.
    - **Not = {42} or (42):** Copy-list-init and parentheses still need static_cast; narrowing is rejected.
    - **using enum (C++20):** Brings a scoped enum's enumerators into namespace, class or block scope.
  - **Active member:** A union holds at most one live member; the language does not track which.
    - **Inactive read is UB:** It reads an object outside its lifetime; constant evaluation rejects it.
    - **Switching members:** Trivial assignment switches; non-trivial members need construct_at and destroy_at.
    - **Common initial sequence:** Standard-layout structs sharing a prefix may read it through either member.
    - **No type punning:** Valid C and a GCC extension, but UB in C++; use std::bit_cast.
  - **Union restrictions:** What a union may and may not contain or do.
    - **No virtuals or bases:** No virtual functions, no base classes, no reference members; never a base.
    - **Non-trivial members:** Delete the matching special members; write the constructor and destructor yourself.
    - **One default initializer:** At most one variant member may have a default member initializer.
    - **Anonymous unions:** Members join the enclosing scope; only public data members, static at namespace scope.
  - **std::variant:** A tagged union that constructs, destroys and checks the active alternative.
    - **Checked access:** std::get with the wrong alternative throws std::bad_variant_access.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.enum], [conv.prom])

Which line is ill-formed?

```cpp
enum Fruit { apple, pear };
enum class Color { red, green };

int a = pear;                          // line A
int b = Color::green;                  // line B
int c = static_cast<int>(Color::red);  // line C
Color d = Color::red;                  // line D
```

A. Line A
B. Line B
C. Line C
D. Line D
E. None of them

**Answer (B):** Line B

**Why:** A scoped enumeration has no implicit conversion to an integer, so initializing an `int` from `Color::green` is ill-formed. The explicit `static_cast` on line C is the intended way, along with `std::to_underlying` in C++23. Line A is fine because unscoped enumerations promote implicitly, and the enumerator `pear` is visible without qualification.

### Question 2 [warmup] ([class.union.general], [basic.life])

What does the C++ standard say about this program?

```cpp
union U { int i; float f; };

int main() {
  U u;
  u.f = 1.0f;
  return u.i;
}
```

A. It returns the bit pattern of `1.0f` reinterpreted as an `int`
B. The value returned is implementation-defined
C. It is ill-formed
D. The behavior is undefined

**Answer (D):** The behavior is undefined

**Why:** Assigning to `u.f` makes `f` the active member, so no `int` object is alive in the union. Reading `u.i` accesses an object outside its lifetime, which is undefined behavior. The first option describes what C guarantees and what GCC documents as an extension, but standard C++ makes no such promise; use `std::bit_cast<int>(1.0f)` instead.

### Question 3 [warmup] ([enum.udecl], [stmt.switch])

In C++20, is this function well-formed?

```cpp
enum class Color { red, green };

int code(Color c) {
  switch (c) {
    using enum Color;
    case red:   return 1;
    case green: return 2;
  }
  return 0;
}
```

A. Yes: `using enum Color;` makes `red` and `green` visible in the switch body
B. No: `using enum` may only appear at namespace scope
C. No: case labels of a scoped enumeration must always be qualified
D. No: a declaration cannot appear before the first case label

**Answer (A):** Yes: `using enum Color;` makes `red` and `green` visible in the switch body

**Why:** `using enum` (P1099, C++20) is a declaration that may appear at namespace, class or block scope, and the switch body is a block. It introduces the enumerators of `Color` as if by a using-declaration for each, so the unqualified case labels find them. A declaration with no initialization before the first label is fine, since no jump bypasses an initialization.

### Question 4 [tricky] ([dcl.init.list], [dcl.enum])

Given `enum class Id : unsigned {};`, which declaration is well-formed in C++17 and later?

A. `Id a = 7;`
B. `Id b(7);`
C. `Id c{7};`
D. `Id d = {7};`

**Answer (C):** `Id c{7};`

**Why:** P0138 (C++17) lets an enumeration with a fixed underlying type be initialized from an integer, but only by direct-list-initialization with a single, non-narrowing element. `Id d = {7};` is copy-list-initialization and is excluded on purpose, which makes it the most tempting wrong answer. Parentheses and `=` still need a `static_cast`.

### Question 5 [tricky] ([expr.static.cast], [dcl.enum])

In C++17 and later, what does the standard say about `x` and `y`?

```cpp
enum Small { a = 1, b = 4 };

Small x = static_cast<Small>(7);
Small y = static_cast<Small>(8);
```

A. Both are well-defined; the values wrap into the underlying type
B. `x` is well-defined; initializing `y` has undefined behavior
C. Both have undefined behavior, because neither value is an enumerator
D. `x` is well-defined; `y` has an unspecified value

**Answer (B):** `x` is well-defined; initializing `y` has undefined behavior

**Why:** `Small` has no fixed underlying type, so its values are those of the smallest bit-field holding 1 and 4: three unsigned bits, 0 to 7. Seven is in range even though no enumerator names it. Eight is out of range, and since C++17 (CWG 1766) the conversion is undefined behavior. The last option was the rule before C++17, when the result was merely unspecified.

### Question 6 [tricky] ([class.union.general], [class.default.ctor], [class.dtor])

Is this program well-formed?

```cpp
#include <string>

union S {
  int i;
  std::string s;
};

int main() {
  S v;
  v.i = 1;
}
```

A. Yes: `i` is the active member, so `s` is never touched
B. No: the union's default constructor and destructor are deleted
C. Yes, but the behavior is undefined because `s` is never constructed
D. No: a union may not have a member of class type

**Answer (B):** No: the union's default constructor and destructor are deleted

**Why:** Since C++11 a union may have members with non-trivial special member functions, but the union's corresponding special members become deleted. `std::string` has a non-trivial default constructor and destructor, and no variant member has a default member initializer, so `S v;` uses a deleted constructor and the program is ill-formed. You must write `S() : i(0) {}` and `~S() {}` yourself and manage `s` by hand.

### Question 7 [standardese] ([class.mem.general], [class.union.general])

What does `main` return?

```cpp
struct A { int tag; double d; };
struct B { int tag; long l; };
union AB { A a; B b; };

int main() {
  AB u{.a = {7, 2.0}};
  return u.b.tag;
}
```

A. Nothing defined: `b` is not the active member, so the read is undefined
B. An implementation-defined value
C. 7
D. An unspecified value

**Answer (C):** 7

**Why:** `A` and `B` are standard-layout structs whose common initial sequence is the `int tag` member. In a standard-layout union whose active member is `a`, reading `b.tag` is permitted and behaves as if `a.tag` were read, so the result is 7. The general rule that reading an inactive member is undefined is what makes the first option tempting; reading `u.b.l` would indeed be undefined.

### Question 8 [standardese] ([expr.const], [class.union.general])

Is the definition of `x` well-formed?

```cpp
union U { int i; float f; };

constexpr float g() {
  U u{.i = 1};
  return u.f;
}

constexpr float x = g();
```

A. No: reading the inactive member is undefined, so `g()` is not a constant expression
B. Yes: `x` holds the float whose bit pattern is the integer 1
C. Yes: `x` is `1.0f`
D. Yes, but the value of `x` is unspecified

**Answer (A):** No: reading the inactive member is undefined, so `g()` is not a constant expression

**Why:** [expr.const] excludes from constant expressions any operation with undefined behavior, and names an lvalue-to-rvalue conversion applied to an inactive union member explicitly. A `constexpr` variable must be initialized by a constant expression, so the definition is ill-formed and compilers must diagnose it. The second option is what type punning would produce at run time on many implementations, which is exactly the guess constant evaluation refuses to make.

---

# Track: Value semantics

What an expression means, when resources move, and when copies disappear at the language level.

# Value categories

> Replace circular left-of-equals folklore with C++17's two orthogonal expression axes—identity and movability—plus temporary materialization and decltype probes.

- **Source:** C++ Atlas (https://cppatlas.com/topics/value-categories)
- **Track:** Value semantics
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [basic.lval] (https://eel.is/c++draft/basic.lval), [conv.rval] (https://eel.is/c++draft/conv.rval), [lex.string] (https://eel.is/c++draft/lex.string), [expr.ref] (https://eel.is/c++draft/expr.ref), [dcl.type.decltype] (https://eel.is/c++draft/dcl.type.decltype), [expr.pre.incr] (https://eel.is/c++draft/expr.pre.incr), [expr.post.incr] (https://eel.is/c++draft/expr.post.incr)
- **cppreference links:** [Value categories](https://en.cppreference.com/w/cpp/language/value_category), [String literal](https://en.cppreference.com/w/cpp/language/string_literal), [decltype specifier](https://en.cppreference.com/w/cpp/language/decltype), [Increment/decrement operators](https://en.cppreference.com/w/cpp/language/operator_incdec), [Copy elision](https://en.cppreference.com/w/cpp/language/copy_elision)
- **Prerequisites:** initialization-forms, casts-and-qualifiers

Traditional C textbooks define lvalues and rvalues by where they sit around an assignment operator. In modern C++, that rule collapses immediately: a `const int` cannot sit on the left of `=`, yet it is an lvalue; meanwhile, a class rvalue like `std::string{} = "ok"` is allowed on the left of `=`, yet it is a prvalue. Every expression in C++—never a variable declaration—belongs to a value category governed by two independent properties.

## Expressions have value categories, not variables

A **variable** has a declared type, such as `int`, `const Widget&`, or `Widget&&`. An **expression** appearing in code has both a non-reference type (references are stripped during expression analysis) and a **value category** (`[basic.lval]`). Keeping those two dimensions separate resolves the single biggest source of confusion around move semantics:

```cpp
#include <utility>

struct Widget {};
void consume(Widget& w);
void consume(Widget&& w);

void relay(Widget&& param) {
    // param's declared type is Widget&&, yet the expression `param` is an lvalue
    consume(param);            // calls consume(Widget&)
    consume(std::move(param)); // std::move returns unnamed Widget&& -> xvalue
}
```

Inside `relay`, `param` has a name and an addressable stack location, so the expression `param` is an **lvalue**, selecting `consume(Widget&)`. Calling `std::move(param)` produces an unnamed `Widget&&`, which is an **xvalue**, selecting `consume(Widget&&)`.

> **Pitfall.** Inside a function body, a parameter declared as `Widget&& param` has type "rvalue reference to `Widget`", yet the expression `param` itself is an lvalue because it has a name and an address.

## The two orthogonal axes: glvalue and rvalue

C++17 organizes value categories around two orthogonal questions:

1. **Has identity (`glvalue`)?** Does evaluating the expression identify a specific object, bit-field, or function whose address or identity can be compared against another?
2. **Can be moved from (`rvalue`)?** Is the expression disposable or explicitly marked expiring so its resources may be safely transferred without another observer noticing?

```text
                  expression
                 /          \
           glvalue          rvalue
           /     \          /    \
       lvalue      xvalue      prvalue
```

Combining these two axes yields three primary, mutually exclusive leaf categories, alongside two compound categories (`glvalue` = `lvalue` or `xvalue`; `rvalue` = `prvalue` or `xvalue`):

| Value category | Has identity (`glvalue`)? | Movable (`rvalue`)? | Addressable with `&`? | Representative expressions |
| --- | --- | --- | --- | --- |
| `lvalue` | Yes | No | Yes (unless bit-field) | `var`, `"cpp"`, `++i`, `func_returning_lref()` |
| `xvalue` | Yes | Yes | Not directly | `std::move(x)`, `Widget{}.member`, `func_returning_rref()` |
| `prvalue` | No | Yes | No | `42`, `Widget{1}`, `i++`, `func_returning_value()` |

> **Mental model.** Every expression falls into one of three leaves: an `lvalue` has durable identity, a `prvalue` is an unmaterialized recipe with no address yet, and an `xvalue` is an existing object whose resources are cleared for reuse.

## Prvalues since C++17: recipes, not objects

Before C++17, a prvalue of class type represented a real temporary object in memory that compilers tried to optimize away. C++17 inverted the model in `[basic.lval]` and `[conv.rval]`. A **prvalue** is no longer an object at all—it is an unmaterialized computation or **initialization recipe** waiting to construct an object directly inside whatever destination slot the caller provides.

A prvalue becomes an actual object in storage—turning into an **xvalue**—only when **temporary materialization conversion** (`[conv.rval]`) fires. Materialization happens at exact language boundaries that demand object identity:

- Binding a reference (`const Widget&` or `Widget&&`) to a prvalue.
- Accessing a non-static data member (`make_widget().id`) or invoking a member function on a prvalue.
- Subscripting a prvalue array (`using A = int[3]; A{1, 2, 3}[0]`).
- Discarding a class or array prvalue as a standalone expression statement (`make_widget();`), so its constructor and destructor still execute deterministically.

If none of those triggers occur—such as `Widget w = make_widget();`—no temporary object is ever created; the prvalue initializes `w` directly in place.

## Tricky expression taxonomy in the wild

Several everyday C++ expressions defy naive intuition until checked against `[basic.lval]`:

- **String literals vs scalar literals**: Numeric, boolean, and `nullptr` literals (`42`, `true`) are prvalues. A string literal such as `"hello"`, however, resides in static storage for the whole program and is an **lvalue** of type `const char[6]` (`[lex.string]`), which is why `&"hello"` compiles cleanly while `&42` is ill-formed.
- **Prefix vs postfix increment**: Built-in `++i` mutates `i` and returns the object itself as an lvalue (`++ ++i` is legal). Built-in `i++` yields a prvalue copy of the old value (`&(i++)` and `i++ = 5` fail to compile).
- **Member access (`E1.E2`)**: Under `[expr.ref]`, if `E1` is an rvalue (prvalue or xvalue) and `E2` names a non-static **object** member, `E1.E2` triggers materialization if needed and produces an **xvalue**. If `E2` is a static data member or a **reference** member (`int& ref;`), `E1.E2` is an **lvalue** because the member's storage outlives `E1` or belongs independently elsewhere.
- **Conditional operator (`cond ? a : b`)**: Yields an lvalue only when both `a` and `b` are lvalues of matching or reference-compatible types; otherwise it yields a prvalue (or xvalue when both match as xvalues).

> **Standardese.** Under `[lex.string]`, a string literal is an lvalue of array type `const char[N]` with static storage duration, whereas numeric, character, and pointer literals are prvalues.

## Probing value categories with decltype

Because `decltype` distinguishes unparenthesized names from general expressions (`[dcl.type.decltype]`), wrapping any expression `e` in an extra pair of parentheses `decltype((e))` turns it into an exact compile-time value-category probe:

- `decltype((e))` yields `T&` if `e` is an **lvalue**.
- `decltype((e))` yields `T&&` if `e` is an **xvalue**.
- `decltype((e))` yields `T` if `e` is a **prvalue**.

```cpp
#include <type_traits>
#include <utility>

struct Box { int value; };
struct AliasBox { int& ref; };

Box make_box();
AliasBox make_alias();

void verify_categories(int i) {
    // Unparenthesized id-expression yields declared type (int), not lvalue category
    static_assert(std::is_same_v<decltype(i), int>);
    // Parenthesized expression probes value category
    static_assert(std::is_same_v<decltype((i)), int&>);             // lvalue
    static_assert(std::is_same_v<decltype((std::move(i))), int&&>); // xvalue
    static_assert(std::is_same_v<decltype((42)), int>);             // prvalue

    static_assert(std::is_same_v<decltype(("hi")), const char (&)[3]>); // lvalue
    static_assert(std::is_same_v<decltype((++i)), int&>);               // lvalue
    static_assert(std::is_same_v<decltype((i++)), int>);                // prvalue
    static_assert(std::is_same_v<decltype((make_box().value)), int&&>);  // xvalue
    static_assert(std::is_same_v<decltype((make_alias().ref)), int&>);   // lvalue
}
```

## What to remember

- Value categories classify expressions, never variables; a named rvalue reference `T&&` evaluates as an lvalue expression.
- `lvalue` = identity without movability; `prvalue` = movability without identity (an unmaterialized initializer); `xvalue` = both identity and movability.
- Temporary materialization (`[conv.rval]`) turns a prvalue into an xvalue only when reference binding, member access, array subscripting, or discarding demands an object in storage.
- String literals are lvalues (`const char[N]`), `E1.E2` on an rvalue yields an xvalue for data members (or an lvalue for reference/static members), and `decltype((expr))` directly reports `T&`, `T&&`, or `T`.

## Concept Map Outline

- **Value categories:** Every C++ expression is classified by object identity and eligibility to be moved from.
  - **Expression vs variable:** Types belong to declarations whereas value categories describe evaluated expressions.
    - **Named T&& parameter:** A named rvalue-reference parameter has type T&& yet evaluates as an lvalue expression.
    - **Function return types:** Calls returning T, T&, and T&& produce prvalues, lvalues, and xvalues respectively.
  - **Two orthogonal axes:** Combining glvalue identity and rvalue movability partitions all expressions into three leaves.
    - **lvalue (glvalue only):** Designates an existing addressable object or function that cannot be implicitly moved.
    - **xvalue (glvalue and rvalue):** Designates an existing expiring object whose resources may be safely transferred.
    - **prvalue (rvalue only):** Represents an unmaterialized computation or initializer with no storage address yet.
  - **Temporary materialization:** C++17 converts a prvalue to an xvalue only when an operation requires object identity.
    - **Reference binding:** Binding const T& or T&& materializes a prvalue into a temporary xvalue.
    - **Member and array access:** Reading a member or subscripting a temporary array triggers materialization first.
    - **Discarded prvalue expression:** Evaluating a standalone class prvalue materializes it so constructor and destructor run.
  - **Subtle expression rules:** Several common C++ expressions break naive left-of-equals intuition.
    - **String vs numeric literals:** String literals are static lvalues of const char[N], whereas numeric literals are prvalues.
    - **Prefix vs postfix ++:** Built-in ++i returns an lvalue to i while i++ yields a prvalue copy.
    - **Member access E1.E2:** A data member on an rvalue yields an xvalue, whereas a reference member yields an lvalue.
  - **decltype probes:** Parenthesized decltype((e)) reveals lvalue, xvalue, or prvalue directly in the type system.
    - **Unparenthesized id-expression:** decltype(x) inspects the declared type of x rather than its expression category.
    - **Parenthesized expression:** decltype((e)) produces T& for lvalues, T&& for xvalues, and T for prvalues.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.lval])

Inside `void f(Widget&& w)`, what is the value category of the expression `w` when passed to `g(w)`?

```cpp
struct Widget {};
void g(Widget&);
void g(Widget&&);
void f(Widget&& w) {
    g(w);
}
```

A. xvalue, because w was declared as Widget&&
B. prvalue, because rvalue parameters hold temporaries
C. lvalue, because w is a named variable with an addressable location
D. glvalue that refuses to bind to either overload

**Answer (C):** lvalue, because w is a named variable with an addressable location

**Why:** Value categories belong to expressions, not types. Even though w has declared type Widget&&, the id-expression w names an object with identity, making it an lvalue that calls g(Widget&).

### Question 2 [warmup] ([expr.pre.incr], [expr.post.incr])

Which built-in increment expression is well-formed in C++ for `int i = 0;`?

```cpp
int i = 0;
```

A. ++ ++i
B. &(i++)
C. (i++) = 3
D. int& r = i++;

**Answer (A):** ++ ++i

**Why:** Built-in prefix ++i increments i and returns i as an lvalue, so ++ ++i compiles and increments i twice. Built-in postfix i++ produces a prvalue copy, which cannot have its address taken, be assigned to, or bind to int&.

### Question 3 [tricky] ([lex.string])

What are the value category and exact type of the string literal `"lucid"`?

```cpp
auto ptr = &"lucid";
```

A. prvalue of type const char*
B. lvalue of type const char[6]
C. prvalue of type const char[6]
D. xvalue of type const char(&)[6]

**Answer (B):** lvalue of type const char[6]

**Why:** Unlike integer or floating literals (which are prvalues), string literals have static storage duration and are lvalues of array type const char[N] including the null terminator, which is why &"lucid" compiles.

### Question 4 [tricky] ([dcl.type.decltype])

Given `int x = 5;`, what types do `decltype(x)` and `decltype((x))` deduce?

```cpp
int x = 5;
using A = decltype(x);
using B = decltype((x));
```

A. A is int, B is int
B. A is int&, B is int&
C. A is int&&, B is int&
D. A is int, B is int&

**Answer (D):** A is int, B is int&

**Why:** Under [dcl.type.decltype], decltype applied to an unparenthesized id-expression returns its declared type (int). Parenthesizing it into (x) triggers the general expression rule, yielding int& for an lvalue.

### Question 5 [standardese] ([expr.ref], [conv.rval])

Given `struct S { int m; int& r; };` and `S make();`, what are the value categories of `make().m` and `make().r`?

```cpp
struct S { int m; int& r; };
S make();
```

A. make().m is an xvalue, and make().r is an lvalue
B. make().m is a prvalue, and make().r is an xvalue
C. Both make().m and make().r are xvalues
D. Both make().m and make().r are lvalues

**Answer (A):** make().m is an xvalue, and make().r is an lvalue

**Why:** Under [expr.ref], make() first undergoes temporary materialization ([conv.rval]) to become an xvalue. A non-static data member access on an rvalue yields an xvalue when the member has object type (m), whereas a member of reference type (r) always yields an lvalue.

### Question 6 [standardese] ([basic.lval], [conv.rval])

In C++17 and later, which statement best describes a class prvalue such as `Widget{42}` before temporary materialization conversion occurs?

A. It is a temporary object allocated in caller stack memory awaiting copy elision
B. It is an unmaterialized initialization recipe with no object identity or storage address yet
C. It is an expiring glvalue whose destructor runs at the next comma operator
D. It is an lvalue stored in static read-only memory

**Answer (B):** It is an unmaterialized initialization recipe with no object identity or storage address yet

**Why:** C++17 redefined prvalues in [basic.lval] as unmaterialized value computations or initializers. A temporary object is only created if temporary materialization conversion ([conv.rval]) is triggered by reference binding, member access, or discarding.

# Copy and move semantics

> How std::move grants permission without moving bytes, when user-declared special members suppress moves, why noexcept unlocks O(1) vector growth, and C++23 simpler implicit move.

- **Source:** C++ Atlas (https://cppatlas.com/topics/copy-and-move)
- **Track:** Value semantics
- **Estimated reading time:** 10 minutes
- **ISO C++ clauses:** [class.copy.ctor] (https://eel.is/c++draft/class.copy.ctor), [class.copy.assign] (https://eel.is/c++draft/class.copy.assign), [class.dtor] (https://eel.is/c++draft/class.dtor), [utility.move] (https://eel.is/c++draft/utility.move), [utility.exchange] (https://eel.is/c++draft/utility.exchange), [utility.move.if.noexcept] (https://eel.is/c++draft/utility.move.if.noexcept), [class.copy.elision] (https://eel.is/c++draft/class.copy.elision)
- **cppreference links:** [Copy constructors](https://en.cppreference.com/w/cpp/language/copy_constructor), [Copy assignment operator](https://en.cppreference.com/w/cpp/language/as_operator), [Move constructors](https://en.cppreference.com/w/cpp/language/move_constructor), [Move assignment operator](https://en.cppreference.com/w/cpp/language/move_assignment), [The rule of three/five/zero](https://en.cppreference.com/w/cpp/language/rule_of_three), [std::move](https://en.cppreference.com/w/cpp/utility/move), [std::move_if_noexcept](https://en.cppreference.com/w/cpp/utility/move_if_noexcept), [std::exchange](https://en.cppreference.com/w/cpp/utility/exchange)
- **Prerequisites:** value-categories

Copying duplicates an object's logical state so two independent owners emerge. Moving transfers ownership from an expiring source—typically copying a few stack pointers or descriptors and resetting the source to a benign empty state—without duplicating heap buffers. Misunderstanding where the compiler generates move operations, when `const` defeats them, or why `noexcept` governs `std::vector` performance turns intended moves into silent deep copies.

## What copying and moving actually do

Calling `std::move(x)` emits zero CPU instructions at runtime. Under `[utility.move]`, `std::move` is simply an unconditional cast to an rvalue reference (`static_cast<std::remove_reference_t<T>&&>(x)`), turning an lvalue expression into an **xvalue**. Only when that xvalue reaches a constructor or assignment operator—or a function overloaded on `T&&`—does any resource transfer actually occur.

> **Mental model.** `std::move` is a permission slip telling overload resolution that the source's resources may be pilfered; it never moves bytes by itself.

That permission slip is easily revoked by `const`. If `s` is declared `const std::string s = "payload";`, then `std::move(s)` produces `const std::string&&`. A move constructor takes non-const `std::string&&` because it must mutate the source, so `const std::string&&` cannot bind to it and silently binds to `const std::string&`, executing a full **copy constructor** instead.

> **Pitfall.** Calling `std::move` on a `const` object compiles cleanly and quietly invokes the copy constructor instead of moving, because `const T&&` cannot bind to a mutable `T&&` move parameter.

## Special member generation rules

C++ tracks six special member functions: default constructor, destructor, copy constructor, copy assignment operator, move constructor, and move assignment operator. Declaring one affects whether the compiler implicitly generates the others (`[class.copy.ctor]`, `[class.copy.assign]`).

| User declaration | Default ctor | Destructor | Copy operations | Move operations |
| --- | --- | --- | --- | --- |
| None | Defaulted | Defaulted | Defaulted | Defaulted |
| Any non-special ctor | Not declared | Defaulted | Defaulted | Defaulted |
| Destructor (`~T`) | Defaulted | User | Defaulted (deprecated if implicit) | Not declared (suppressed) |
| Copy ctor or copy assign | Same unless copy ctor | Defaulted | User / defaulted | Not declared (suppressed) |
| Move ctor or move assign | Same unless move ctor | Defaulted | Deleted | User / defaulted |

Two interactions catch experienced engineers off guard:

1. **Declaring a destructor suppresses implicit moves.** Even writing `~Buffer() = default;` in a class header disables implicit generation of both the move constructor and the move assignment operator. Any move request falls back to calling the copy constructor, silently turning O(1) transfers into O(N) deep copies—or failing to compile if a member such as `std::unique_ptr` is non-copyable.
2. **Declaring a move operation deletes copying.** Adding a custom move constructor (`T(T&&)`) marks both the copy constructor and copy assignment operator as implicitly `= delete` unless you explicitly declare or `= default` them.

Follow the **Rule of Zero** whenever possible: store resources in standard RAII wrappers (`std::unique_ptr`, `std::vector`, `std::string`) and declare none of the five ownership members. When building a low-level RAII handle directly, follow the **Rule of Five** and declare all five explicitly.

## Implementing move operations cleanly and exception-safely

A hand-written move operation must transfer ownership, leave the source safely destructible and assignable, and handle **self-move assignment** (`a = std::move(a)`, which generic sorting or partition algorithms can trigger). Standard library helper `std::exchange(obj, new_val)` from `<utility>` replaces a member with a null or sentinel value and returns its old value in one step:

```cpp
#include <cstddef>
#include <utility>

class Buffer {
    int* data_ = nullptr;
    std::size_t size_ = 0;

public:
    Buffer() = default;
    explicit Buffer(std::size_t n) : data_(n ? new int[n]{} : nullptr), size_(n) {}
    ~Buffer() { delete[] data_; }

    Buffer(const Buffer&) = delete;
    Buffer& operator=(const Buffer&) = delete;

    Buffer(Buffer&& other) noexcept
        : data_(std::exchange(other.data_, nullptr)),
          size_(std::exchange(other.size_, 0)) {}

    Buffer& operator=(Buffer&& other) noexcept {
        if (this == &other) {
            return *this;
        }
        delete[] data_;
        data_ = std::exchange(other.data_, nullptr);
        size_ = std::exchange(other.size_, 0);
        return *this;
    }
};
```

Wait before reading anything out of a moved-from standard library object. Under `[lib.types.movedfrom]`, a moved-from standard type is guaranteed to be in a **valid but unspecified state**: you can destroy it, assign a fresh value to it, or invoke precondition-free observers such as `clear()`, while assuming `vec.empty()` without checking is a logic bug unless a specific type documents it (like `std::unique_ptr`, which guarantees `get() == nullptr`).

## The noexcept cliff and std::move_if_noexcept

Containers such as `std::vector` enforce the **strong exception guarantee** during reallocation (`push_back` or `reserve`): if migrating elements from the old buffer to the new buffer throws an exception midway, the original vector must remain completely intact.

If moving element `k` threw after elements `0` through `k - 1` had already been moved from, rolling back could itself throw. To prevent data loss, `std::vector` moves elements via `std::move_if_noexcept` (`[utility.move.if.noexcept]`), which yields `T&&` **only** when `std::is_nothrow_move_constructible_v<T>` is true—or when `T` is not copy-constructible at all. Otherwise, it returns `const T&` and forces `std::vector` to copy every element!

```cpp
#include <type_traits>
#include <utility>

struct ThrowingMove {
    ThrowingMove(const ThrowingMove&) {}
    ThrowingMove(ThrowingMove&&) {} // Missing noexcept!
};

struct SafeMove {
    SafeMove(const SafeMove&) {}
    SafeMove(SafeMove&&) noexcept {}
};

static_assert(std::is_same_v<decltype(std::move_if_noexcept(std::declval<ThrowingMove&>())),
                             const ThrowingMove&>);
static_assert(std::is_same_v<decltype(std::move_if_noexcept(std::declval<SafeMove&>())),
                             SafeMove&&>);
```

Compiler-defaulted move constructors (`= default`) automatically compute `noexcept` from their members and bases. Hand-written move constructors and move assignment operators must spell `noexcept` explicitly.

## Implicit move on return from C++11 through C++23

When returning a named automatic variable or function parameter by value (`return local;`), compilers try copy elision first if permitted. When elision does not occur—for example, returning a function parameter or converting a local variable to another type—`[class.copy.elision]` performs **implicit move**: overload resolution runs a first pass treating the returned local or parameter as an rvalue, falling back to an lvalue only if no viable rvalue match exists.

C++23 (P2266R3) simplified these rules cleanly around **move-eligible** expressions in `return`, `co_return`, and `throw`. Previously, implicit move only applied to constructors returning the exact type or compatible types under awkward special-case wording, failing on user-defined rvalue conversion operators or returning rvalue references:

```cpp
struct Output {};
struct Builder {
    operator Output() && { return Output{}; }
    operator Output() const& = delete;
};

Output finalize(Builder b) {
    return b; // Compiles in C++23 (P2266R3); failed in C++20
}
```

> **Standardese.** Under `[class.copy.elision]`, an id-expression naming an automatic variable or parameter in a `return` or `throw` statement is move-eligible, so overload resolution treats it as an rvalue first without needing `std::move`.

## What to remember

- `std::move` casts an lvalue to an xvalue (`T&&`) at compile time; calling it on a `const` object produces `const T&&` and silently copies.
- Any user-declared destructor or copy operation suppresses implicit move generation; any user-declared move operation deletes implicit copy operations.
- Always mark non-throwing move constructors and move assignment operators `noexcept` so `std::move_if_noexcept` lets containers move instead of copy during reallocation.
- Leave moved-from objects valid, destructible, and self-move safe using `std::exchange`, and omit `std::move` on `return local;` so NRVO and C++23 implicit move both work cleanly.

## Concept Map Outline

- **Copy and move semantics:** Move semantics transfers ownership from expiring objects while respecting constness and exception safety.
  - **std::move and constness:** std::move only casts to an rvalue reference and yields to copy semantics on const objects.
    - **Unconditional rvalue cast:** std::move produces an xvalue at compile time without emitting runtime instructions.
    - **const T&& fallback:** Applying std::move to a const variable creates const T&&, which calls the copy constructor.
  - **Special member generation:** User-declared destructors, copies, or moves alter which special members the compiler generates.
    - **Destructor suppresses move:** Declaring any destructor disables implicit move generation and falls back to copying.
    - **Move deletes copy:** Declaring a custom move operation implicitly deletes copy construction and copy assignment.
    - **Rule of Zero vs Five:** Compose RAII wrappers to avoid custom members, or explicitly define all five for raw handles.
  - **Safe move implementation:** Custom move operations must clear the source, survive self-assignment, and preserve invariants.
    - **std::exchange:** Atomically steals a pointer or handle value while resetting the source member to null.
    - **Self-move guard:** Checking this == &other prevents freeing your own buffer during a = std::move(a).
    - **Valid unspecified state:** Moved-from standard objects remain destructible and assignable without guaranteeing emptiness.
  - **noexcept and containers:** Containers use std::move_if_noexcept to preserve strong exception safety during reallocation.
    - **std::move_if_noexcept:** Selects rvalue move only if the move constructor is noexcept or copying is unavailable.
    - **Explicit noexcept required:** User-written move operations do not infer noexcept automatically and must annotate it.
  - **Implicit move on return:** Returning a local variable or parameter automatically attempts rvalue overload resolution first.
    - **C++23 P2266R3 rules:** Simpler implicit move treats move-eligible id-expressions uniformly as rvalues across conversions.

## Standardese Quiz Questions

### Question 1 [warmup] ([utility.move])

What does `std::move(x)` actually do at runtime when executed on a local `std::vector<int> x`?

```cpp
std::vector<int> a{1, 2, 3};
auto b = std::move(a);
```

A. std::move copies the heap pointer and zeroes a inside the std::move function body
B. std::move emits zero instructions; it simply casts a to an xvalue so vector's move constructor is selected
C. std::move immediately invokes a.~vector() after returning
D. std::move swaps the stack frames of a and b

**Answer (B):** std::move emits zero instructions; it simply casts a to an xvalue so vector's move constructor is selected

**Why:** std::move is a pure compile-time cast to std::remove_reference_t<T>&& ([utility.move]). The actual pointer transfer and zeroing happen inside std::vector's move constructor because overload resolution picks vector(vector&&) for the xvalue.

### Question 2 [warmup] ([utility.move], [dcl.init.ref])

What happens when you initialize `b` using `const std::string a = "hello"; std::string b = std::move(a);`?

```cpp
const std::string a = "hello";
std::string b = std::move(a);
```

A. Compilation fails because you cannot pass a const object to std::move
B. std::string's move constructor runs and clears a
C. std::string's copy constructor runs because std::move(a) has type const std::string&&
D. Undefined behavior from modifying a const object

**Answer (C):** std::string's copy constructor runs because std::move(a) has type const std::string&&

**Why:** std::move(a) preserves constness and returns const std::string&&. Because std::string(std::string&&) requires a non-const rvalue reference, overload resolution selects std::string(const std::string&) and copies a.

### Question 3 [tricky] ([utility.move.if.noexcept], [vector.modifiers])

Why does `std::vector<Item>::push_back` copy existing `Item` elements during reallocation when `Item` declares both `Item(const Item&)` and `Item(Item&&)` without `noexcept`?

```cpp
struct Item {
    Item(const Item&);
    Item(Item&&); // not noexcept
};
```

A. std::vector never moves elements during reallocation; it always copies
B. std::vector uses std::move_if_noexcept, which falls back to copying so the old buffer stays intact if moving throws mid-reallocation
C. Non-noexcept move constructors are treated as deleted by std::allocator
D. Because Item lacks a user-declared destructor, its move constructor is suppressed

**Answer (B):** std::vector uses std::move_if_noexcept, which falls back to copying so the old buffer stays intact if moving throws mid-reallocation

**Why:** To preserve push_back's strong exception guarantee, std::vector calls std::move_if_noexcept ([utility.move.if.noexcept]). Because Item has a copy constructor and its move constructor is not noexcept, move_if_noexcept yields const Item& and copies safely.

### Question 4 [tricky] ([class.copy.ctor], [class.copy.assign])

What is the effect of adding `~Widget() = default;` to a struct that has a `std::string` member and no explicitly declared copy or move functions?

```cpp
struct Widget {
    std::string name;
    ~Widget() = default;
};
```

A. Both copy and move operations remain implicitly defaulted as before
B. Copy operations are deleted while move operations remain defaulted
C. Move constructor and move assignment are implicitly deleted
D. Implicit move constructor and move assignment are not declared (suppressed), so moving Widget silently calls its copy operations

**Answer (D):** Implicit move constructor and move assignment are not declared (suppressed), so moving Widget silently calls its copy operations

**Why:** Under [class.copy.ctor] and [class.copy.assign], any user-declared destructor suppresses implicit declaration of both the move constructor and move assignment operator. Implicit copy operations remain declared, so moves quietly degrade into copies.

### Question 5 [standardese] ([lib.types.movedfrom])

What does the C++ standard guarantee about a moved-from `std::string s` after `auto t = std::move(s);`?

A. s is in a valid but unspecified state: it can be safely destroyed or reassigned, though its contents and length are unspecified
B. s is guaranteed to have s.empty() == true and s.capacity() == 0
C. Using s in any way—including destruction—is undefined behavior
D. s retains its original characters until s goes out of scope

**Answer (A):** s is in a valid but unspecified state: it can be safely destroyed or reassigned, though its contents and length are unspecified

**Why:** [lib.types.movedfrom] specifies that moved-from standard library objects are placed in a valid but unspecified state unless explicitly specified otherwise. Calling clear() or assigning a new value is safe; assuming empty() is not.

### Question 6 [standardese] ([class.copy.elision])

Why does `Output finalize(Builder b) { return b; }` compile in C++23 when `Builder` defines only `operator Output() &&` and deletes `operator Output() const&`?

```cpp
struct Output {};
struct Builder {
    operator Output() && { return {}; }
    operator Output() const& = delete;
};
Output finalize(Builder b) { return b; }
```

A. NRVO eliminates the conversion operator entirely for function parameters
B. C++23 P2266R3 classifies b in return b as move-eligible, so overload resolution treats b as an rvalue during implicit move
C. Parameters passed by value are always prvalues inside the function body
D. Because operator Output() const& is deleted, the compiler calls reinterpret_cast

**Answer (B):** C++23 P2266R3 classifies b in return b as move-eligible, so overload resolution treats b as an rvalue during implicit move

**Why:** Under C++23 [class.copy.elision] (P2266R3), an id-expression naming an automatic variable or parameter in a return statement is move-eligible, triggering an rvalue-first overload lookup that picks operator Output() && without needing std::move(b).

# Copy elision and NRVO

> Why C++17 guaranteed prvalue elision eliminates moves by language semantics rather than optimization, and how optional NRVO breaks when you write return std::move(x).

- **Source:** C++ Atlas (https://cppatlas.com/topics/copy-elision)
- **Track:** Value semantics
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [class.copy.elision] (https://eel.is/c++draft/class.copy.elision), [basic.lval] (https://eel.is/c++draft/basic.lval), [conv.rval] (https://eel.is/c++draft/conv.rval), [dcl.init] (https://eel.is/c++draft/dcl.init), [expr.call] (https://eel.is/c++draft/expr.call)
- **cppreference links:** [Copy elision](https://en.cppreference.com/w/cpp/language/copy_elision), [Value categories](https://en.cppreference.com/w/cpp/language/value_category), [return statement](https://en.cppreference.com/w/cpp/language/return), [Copy-initialization](https://en.cppreference.com/w/cpp/language/copy_initialization), [Direct-initialization](https://en.cppreference.com/w/cpp/language/direct_initialization)
- **Prerequisites:** value-categories, copy-and-move

Copy elision began in C++98 as a compiler permission slip: the compiler could skip calling a copy constructor when constructing from a temporary, yet the language still forced that copy constructor to exist and be accessible. C++17 split that single rule into two fundamentally different mechanisms: **guaranteed prvalue initialization**, where no copy or move ever exists in the abstract machine, and **optional elision** such as NRVO, where a real local object's construction may still be fused into the caller's destination.

## From compiler optimization to language guarantee

Prior to C++17, returning a `std::mutex` or non-movable lock guard by value from a factory function failed to compile. Even when `-O2` elided every copy instruction in machine code, the front-end checked whether an accessible copy or move constructor existed before eliding it.

C++17 fixed this by redefining **prvalues** (`[basic.lval]`, `[dcl.init]`). Because a prvalue is an unmaterialized initializer rather than an object in storage, returning `T{args...}` passes the initialization recipe directly down to the caller's target object slot.

> **Mental model.** Guaranteed copy elision does not delete a move constructor call—it passes the destination memory address down the prvalue chain so only one object is ever constructed.

## Mandatory prvalue elision in C++17 and beyond

Under `[dcl.init]` and `[conv.rval]`, whenever an object of class type `T` is initialized from a prvalue whose cv-unqualified type is also `T`, no temporary object is materialized at all. You can chain arbitrarily many factory functions returning by value, pass prvalues into value parameters (`take(make())`), or allocate via `new T(make())`, and none of them require a copy or move constructor:

```cpp
struct NonMovable {
    int token;
    explicit NonMovable(int t) : token(t) {}
    NonMovable(const NonMovable&) = delete;
    NonMovable(NonMovable&&) = delete;
};

NonMovable make_inner() { return NonMovable{42}; }
NonMovable make_outer() { return make_inner(); }
void consume(NonMovable nm) { (void)nm.token; }

void mandatory_elision_demo() {
    NonMovable direct = make_outer(); // Constructs directly into `direct`
    consume(make_outer());            // Constructs directly into parameter `nm`
    (void)direct;
}
```

Four boundaries mark where mandatory prvalue elision **stops** applying:

- **Assignment (`target = make_outer();`)**: `target` is already alive, so `make_outer()` materializes a temporary xvalue and invokes `operator=`.
- **Type mismatch (`Base b = make_derived();`)**: When the destination type differs from the prvalue's type, materialization occurs to construct `Derived` and then `Base(Derived&&)` (object slicing) runs.
- **Returning a named variable (`return local;`)**: `local` is an lvalue, not a prvalue, shifting the situation from mandatory elision to optional NRVO.
- **No-unique-address members or base subobjects**: Initializing a base subobject or a `[[no_unique_address]]` member from a prvalue may still materialize a temporary on some ABIs because tail padding can overlap sibling data.

> **Standardese.** Under `[dcl.init]`, when initializing an object of class type from a prvalue of the same cv-unqualified class type, the initializer expression directly initializes the target object without materializing a temporary.

## NRVO and optional compiler elision

When a function constructs a **named** automatic local object and returns it (`return buf;`), that object already owns storage in the function's stack frame unless the compiler places `buf` directly in the caller's return-value slot. That transformation is **Named Return Value Optimization (NRVO)** (`[class.copy.elision]`).

| Mechanism | Applies to | Copy or move ctor required? | Guaranteed by ISO C++? | Observable ctor/dtor side effects skipped? |
| --- | --- | --- | --- | --- |
| Mandatory prvalue init | Unnamed prvalue of same cv-unqualified type | No (even if `= delete`) | Yes (C++17+) | Yes, no extra object exists |
| NRVO | Named local automatic object of same return type | Yes, must be accessible | No (permitted only) | Yes, when compiler applies NRVO |
| Implicit move | Named local or parameter when elision is not used | Yes (rvalue overload first) | Yes (overload order) | No, move ctor runs |

Beyond NRVO, `[class.copy.elision]` permits optional elision in two exception-handling cases: throwing an automatic local variable (`throw err;`) into the exception object, and catching an exception by value (`catch (MyError e)`) directly sharing storage with the active exception object—again, only when a copy or move constructor is accessible.

## What breaks NRVO and how to keep it

Because NRVO is an optional optimization rather than a language guarantee, small structural choices prevent compilers from fusing a local variable into the return slot:

1. **Writing `return std::move(local);`**: NRVO requires the `return` operand to be the unparenthesized name of a non-volatile automatic variable. Wrapping it in `std::move(local)` turns the operand into a function call returning an xvalue, **disabling NRVO** and forcing an actual move constructor call (flagged by `-Wpessimizing-move`).
2. **Returning a function parameter (`return param;`)**: Function parameters reside in caller- or ABI-dictated parameter slots, so `[class.copy.elision]` forbids NRVO on parameters—though implicit move still selects the move constructor.
3. **Returning different local variables on multiple branches (`if (ok) return a; return b;`)**: A single return slot cannot simultaneously alias two distinct live objects `a` and `b`, so compilers usually disable NRVO on at least one branch.
4. **Returning a member subobject or static/global variable (`return pair.first;`)**: Neither is an automatic variable matching the return type's whole storage.

> **Pitfall.** Writing `return std::move(local);` blocks NRVO and forces a runtime move construction where plain `return local;` constructs directly in the caller's slot—and already uses implicit move whenever NRVO cannot run.

## Compilable proof: prvalues vs named locals

Testing `NonMovable` side by side highlights the exact boundary between C++17's language guarantee and optional NRVO:

```cpp
struct NonMovable {
    int id;
    explicit NonMovable(int v) : id(v) {}
    NonMovable(const NonMovable&) = delete;
    NonMovable(NonMovable&&) = delete;
};

NonMovable ok_prvalue(bool flag) {
    if (flag) {
        return NonMovable{1}; // Guaranteed: direct in-place init
    }
    return NonMovable{2};     // Guaranteed: separate prvalue branch
}

/* Ill-formed even though NRVO could optimize it in release builds:
NonMovable broken_nrvo() {
    NonMovable local{3};
    return local; // Error: NonMovable(NonMovable&&) is deleted!
}
*/
```

Even though an optimizing compiler would gladly apply NRVO to `broken_nrvo()`, the standard forbids relying on NRVO for legality because another build configuration (or `-fno-elide-constructors`) must still have a valid move or copy constructor to fall back on. Only when returning an unmaterialized prvalue—even across multiple `if` branches—does C++17 guarantee that no copy or move constructor is ever needed.

## What to remember

- Guaranteed copy elision in C++17+ applies to prvalues of the same cv-unqualified class type and works even when copy and move constructors are `= delete`.
- Assignment (`x = make()`), type mismatches (`Base b = make_derived()`), and named local variables (`return local;`) do not trigger guaranteed prvalue elision.
- NRVO is permitted but never guaranteed, so returned named locals still require an accessible copy or move constructor.
- Never write `return std::move(local);`: it disables NRVO, whereas plain `return local;` gets NRVO when possible and implicit move automatically otherwise.

## Concept Map Outline

- **Copy elision and NRVO:** C++17 separates guaranteed prvalue initialization from optional compiler elision such as NRVO.
  - **Mandatory prvalue elision:** Prvalues are unmaterialized initializers that construct directly inside the destination slot.
    - **No ctor required:** Types with deleted copy and move constructors can still be returned by prvalue.
    - **Chained factory calls:** Nested prvalue returns forward the target slot without creating intermediate objects.
    - **Where it stops:** Assignment, slicing conversions, and named locals still require assignment or ctors.
  - **Optional NRVO:** Compilers may fuse a named automatic local variable directly into the caller return slot.
    - **Accessible ctor needed:** Because NRVO is optional, the returned type must still expose a copy or move constructor.
    - **Throw and catch elision:** The standard also permits eliding copies when throwing locals or catching by value.
  - **What disables NRVO:** Several common patterns prevent the compiler from aliasing a local with the return slot.
    - **return std::move(local):** Casting the returned variable to an xvalue blocks NRVO and forces an explicit move.
    - **Function parameters:** ABI parameter storage forbids NRVO on parameters, though implicit move still applies.
    - **Multiple distinct locals:** Returning different local variables on separate branches usually defeats NRVO.
    - **Members and globals:** Subobjects and non-automatic objects cannot occupy the caller return slot directly.
  - **Implicit move fallback:** When NRVO does not run, plain return local tries rvalue move resolution automatically.
    - **Rvalue-first overload lookup:** Overload resolution tries treating the returned local or parameter as an rvalue first.
    - **C++23 P2266R3 rule:** Simpler implicit move treats move-eligible id-expressions uniformly across return conversions.
    - **Best practice rule:** Write plain return local to preserve NRVO when possible and implicit move otherwise.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.init], [basic.lval])

Why does returning `NonMovable{42}` from `NonMovable make()` compile in C++17+ even though both its copy and move constructors are `= delete`?

```cpp
struct NonMovable {
    NonMovable(int);
    NonMovable(const NonMovable&) = delete;
    NonMovable(NonMovable&&) = delete;
};
NonMovable make() { return NonMovable{42}; }
```

A. Because C++17 ignores = delete inside return statements
B. Because NonMovable{42} is a prvalue that directly initializes the caller's target slot without materializing or moving a temporary
C. Because NRVO automatically synthesizes a private move constructor
D. Because return NonMovable{42} calls memcpy on the stack frame

**Answer (B):** Because NonMovable{42} is a prvalue that directly initializes the caller's target slot without materializing or moving a temporary

**Why:** Since C++17 ([basic.lval], [dcl.init]), a prvalue is an unmaterialized initializer rather than a temporary object. Initializing a NonMovable destination from a NonMovable prvalue constructs directly in place with zero copy or move calls.

### Question 2 [warmup] ([class.copy.elision])

What is the practical effect of writing `return std::move(s);` when `s` is a local `std::string` inside `std::string build()`?

```cpp
std::string build() {
    std::string s = "long heap string";
    return std::move(s);
}
```

A. It triggers guaranteed copy elision by converting s into a prvalue
B. It speeds up the function because plain return s would copy s
C. It prevents NRVO and forces a move construction instead of zero-cost in-place construction
D. It causes undefined behavior because s is destroyed before the move finishes

**Answer (C):** It prevents NRVO and forces a move construction instead of zero-cost in-place construction

**Why:** NRVO applies only when the return operand is the plain name of a local automatic variable. std::move(s) turns it into a function call xvalue, disabling NRVO and forcing a move constructor (-Wpessimizing-move).

### Question 3 [tricky] ([class.copy.elision], [dcl.init])

In C++23, which snippet fails to compile when `Token` has deleted copy and move constructors?

```cpp
struct Token {
    explicit Token(int);
    Token(const Token&) = delete;
    Token(Token&&) = delete;
};
```

A. Token a = Token{1};
B. Token make() { return Token{2}; } Token b = make();
C. Token bad() { Token t{3}; return t; }
D. void f(Token); f(Token{4});

**Answer (C):** Token bad() { Token t{3}; return t; }

**Why:** Returning a named local variable t relies on optional NRVO, not guaranteed prvalue elision. Because NRVO is optional under [class.copy.elision], the language still requires an accessible copy or move constructor for t.

### Question 4 [tricky] ([class.copy.elision])

Given `std::string passthrough(std::string param) { return param; }`, what happens in the `return param;` statement?

```cpp
std::string passthrough(std::string param) {
    return param;
}
```

A. Mandatory prvalue elision constructs param directly in the caller's return slot
B. NRVO applies because param is a named variable inside passthrough
C. Copy constructor runs because param is an lvalue
D. NRVO is forbidden on function parameters, so implicit move invokes std::string(std::string&&)

**Answer (D):** NRVO is forbidden on function parameters, so implicit move invokes std::string(std::string&&)

**Why:** Under [class.copy.elision], NRVO excludes function parameters because parameter storage lives in the caller/ABI frame. However, param is move-eligible, so implicit move constructs the return object using std::string's move constructor.

### Question 5 [standardese] ([dcl.init], [conv.rval])

Suppose `Derived` publicly inherits from `Base` and `Derived make_derived();` returns a prvalue. Does `Base b = make_derived();` bypass `Base`'s move constructor via mandatory copy elision?

```cpp
struct Base { Base(const Base&) = delete; Base(Base&&) = delete; };
struct Derived : Base {};
Derived make_derived();
```

A. No; mandatory prvalue elision requires the prvalue's cv-unqualified type to match Base, so make_derived() materializes and fails because Base(Base&&) is deleted
B. Yes; mandatory elision constructs only the Base subobject directly in b
C. Yes, provided Derived adds no data members
D. No; it invokes reinterpret_cast<Base&&>(make_derived())

**Answer (A):** No; mandatory prvalue elision requires the prvalue's cv-unqualified type to match Base, so make_derived() materializes and fails because Base(Base&&) is deleted

**Why:** [dcl.init] grants direct initialization without temporary materialization only when the prvalue has the same cv-unqualified class type as the destination object. When constructing Base from a Derived prvalue, Derived materializes via [conv.rval] and Base's deleted move constructor makes the initialization ill-formed.

### Question 6 [standardese] ([conv.rval], [dcl.init])

Which statement about `x = make_widget();` (copy assignment to an already-constructed `Widget x`) is accurate under C++23?

```cpp
struct Widget {};
Widget make_widget();
void assign() {
    Widget x;
    x = make_widget();
}
```

A. Mandatory copy elision constructs the return value of make_widget() directly on top of x without calling operator=
B. make_widget() undergoes temporary materialization conversion ([conv.rval]) to an xvalue, and Widget::operator=(Widget&&) (or const Widget&) is called
C. x is automatically destroyed and placement-newed via NRVO
D. Assignment to an existing object is ill-formed if make_widget() returns a prvalue

**Answer (B):** make_widget() undergoes temporary materialization conversion ([conv.rval]) to an xvalue, and Widget::operator=(Widget&&) (or const Widget&) is called

**Why:** Mandatory prvalue elision applies only to initialization of a new object, never assignment to an existing object. Because operator= takes a reference parameter, temporary materialization ([conv.rval]) creates a temporary xvalue bound to operator='s parameter.

# Reference binding and temporaries

> Which expressions bind to T&, const T&, and T&&, when implicit conversions silently materialize fresh temporaries, why lifetime extension stops at function boundaries, and C++23 range-for fixes.

- **Source:** C++ Atlas (https://cppatlas.com/topics/reference-binding-and-temporaries)
- **Track:** Value semantics
- **Estimated reading time:** 10 minutes
- **ISO C++ clauses:** [dcl.init.ref] (https://eel.is/c++draft/dcl.init.ref), [class.temporary] (https://eel.is/c++draft/class.temporary), [stmt.ranged] (https://eel.is/c++draft/stmt.ranged), [dcl.ref] (https://eel.is/c++draft/dcl.ref), [meta.unary.prop] (https://eel.is/c++draft/meta.unary.prop)
- **cppreference links:** [Reference initialization](https://en.cppreference.com/w/cpp/language/reference_initialization), [Reference declaration](https://en.cppreference.com/w/cpp/language/reference), [Lifetime](https://en.cppreference.com/w/cpp/language/lifetime), [Range-based for loop](https://en.cppreference.com/w/cpp/language/range-for), [Implicit conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion), [std::reference_constructs_from_temporary](https://en.cppreference.com/w/cpp/types/reference_constructs_from_temporary), [std::reference_converts_from_temporary](https://en.cppreference.com/w/cpp/types/reference_converts_from_temporary)
- **Prerequisites:** value-categories, casts-and-qualifiers

References look like simple aliases, yet two rules make them a prime source of silent dangling bugs: references can trigger implicit conversions that materialize unexpected temporary objects, and lifetime extension stops abruptly across function calls and constructors. Knowing exactly when a reference aliases an existing object versus when it anchors a freshly created temporary prevents subtle use-after-free bugs.

## The reference-binding matrix

C++ offers four reference types with strict rules over which value categories and cv-qualifications they accept (`[dcl.init.ref]`). Note that `const T&&` exists in the grammar, though almost its only practical use is writing `= delete` overloads (such as `std::as_const(const T&&) = delete;`) to reject rvalues cleanly.

| Reference parameter | Mutable `lvalue` (`T`) | `const lvalue` (`const T`) | Mutable `xvalue` / `prvalue` (`T`) | `const xvalue` / `prvalue` (`const T`) |
| --- | --- | --- | --- | --- |
| `T&` | Binds directly | Rejected | Rejected | Rejected |
| `const T&` | Binds directly | Binds directly | Binds (materializes prvalue) | Binds (materializes prvalue) |
| `T&&` | Rejected | Rejected | Binds (materializes prvalue) | Rejected |
| `const T&&` | Rejected | Rejected | Binds (materializes prvalue) | Binds (materializes prvalue) |

Two rules stand out immediately:

1. Non-const `T&` refuses rvalues because mutating an expiring temporary through a caller's output parameter is almost always a bug.
2. `const T&` binds every value category—and goes even further by invoking implicit conversions when types do not match directly.

> **Mental model.** A reference does not necessarily alias the exact expression you wrote; when types differ or a prvalue appears, `const T&` and `T&&` may silently materialize a brand-new temporary object just for the reference to hold onto.

## Silent temporaries during implicit conversion

Because `const T&` accepts convertible expressions of a different type, writing `double ratio = 3.75; const int& r = ratio;` compiles cleanly—and creates a **brand-new `int{3}` temporary** on the stack rather than aliasing `ratio`. Updating `ratio = 9.5;` leaves `r` equal to `3`! The exact same temporary materialization happens when passing `"hello"` to a function expecting `const std::string&`: a temporary `std::string` allocates, copies `"hello"`, binds to the parameter, and destroys when the full-expression ends.

> **Pitfall.** Binding `const T&` to a different or convertible type creates a hidden temporary object rather than aliasing the original variable—and silently dangles if stored in a reference member or returned from a function.

C++23 introduced `<type_traits>` predicates `std::reference_constructs_from_temporary_v<T, U>` and `std::reference_converts_from_temporary_v<T, U>` (`[meta.unary.prop]`) so generic containers like `std::tuple` and `std::pair` can detect and reject dangling bindings at compile time. Note carefully that passing a non-reference `U` (such as `std::string`) checks binding from a `U` **prvalue** (which does materialize a temporary), whereas `std::string&` checks an lvalue:

```cpp
#include <string>
#include <type_traits>

static_assert(std::reference_converts_from_temporary_v<const int&, double>);
static_assert(std::reference_converts_from_temporary_v<const std::string&, const char*>);
static_assert(std::reference_converts_from_temporary_v<const std::string&, std::string>);
static_assert(!std::reference_converts_from_temporary_v<const std::string&, std::string&>);

void implicit_temp_proof() {
    double d = 3.75;
    const int& r = d; // Binds to a temporary int{3}, NOT to d
    d = 9.5;          // r still reads 3!
    (void)r;
}
```

## Temporary lifetime and direct lifetime extension

Under `[class.temporary]`, temporary objects materialized during a full-expression are destroyed as the last step of evaluating that full-expression (typically at the semicolon), in strict reverse order of their creation.

A single narrow rule alters that schedule: **direct lifetime extension** (`[class.temporary]`). When a temporary is bound **directly** to a local reference variable (`const T&` or `T&&`), that temporary's lifetime extends to match the lifetime of the reference itself—including when binding to a direct non-static data member subobject (`const int& id = make_pair().first;`) or initializing a reference field of an aggregate (`struct View { const std::string& s; }; View v{"hi"};`). Notice that in `const int& id = make_pair().first;`, the **entire** `std::pair` temporary stays alive until `id` leaves scope, not only `.first`.

> **Standardese.** Under `[class.temporary]`, when a reference binds directly to a temporary prvalue or a member subobject thereof, that temporary's lifetime expands to match the reference's scope—except across specific syntactic boundaries listed by the standard.

## Five boundaries where lifetime extension stops

Lifetime extension is shallow and purely syntactic. The moment indirection enters, the temporary resumes dying at the full-expression's semicolon:

1. **Passing through a function returning a reference**: In `const T& r = identity(make_t());` (where `identity` returns `const T&`), the compiler cannot track provenance across function bodies, so `make_t()` dies at the semicolon and `r` dangles immediately.
2. **Member accessors and views (`make_vec().front()` or `std::string_view(make_str())`)**: Because `.front()` and `std::string_view` conversion are function calls rather than direct member subobject accesses, the owning `vector` or `string` dies at the semicolon while `r` or the view still points into freed storage.
3. **Constructor member initializers**: Binding a temporary to a reference member inside a constructor initializer list (`Holder(const T& t) : ref(t) {}` or `Holder() : ref(T{}) {}`) never extends the temporary beyond the constructor's full-expression.
4. **`return` statements**: Binding a local reference inside a `return` statement (`const T& x = make_t(); return x;`) destroys the temporary when the function stack frame unwinds.
5. **`new` expressions**: Temporaries bound within a `new` initializer do not outlive the full-expression containing `new`.

```cpp
#include <string>
#include <vector>

struct Wrapper {
    std::vector<int> items{10, 20, 30};
    const std::vector<int>& get_items() const { return items; }
};

Wrapper make_wrapper() { return Wrapper{}; }

void boundary_demo() {
    // Extended: direct binding to data member subobject of temporary Wrapper
    const std::vector<int>& safe = make_wrapper().items;

    // DANGLES immediately at semicolon: get_items() is a function call!
    // const std::vector<int>& bad = make_wrapper().get_items();
    (void)safe;
}
```

## Range-based for loops and C++23 P2718

For over a decade, range-based `for` loops suffered from one of C++'s sharpest traps. Because `for (auto x : range_expr)` expands roughly to `auto&& __range = range_expr;`, any outer temporary behind a chained accessor died at the semicolon **before the first loop iteration ever executed**:

```cpp
#include <vector>

struct RangeBox {
    std::vector<int> items{1, 2, 3};
    const std::vector<int>& get_items() const { return items; }
};

RangeBox make_box() { return RangeBox{}; }

// Pre-C++23: UB! RangeBox temporary died before the loop body started!
// C++23 (P2718R0): Well-defined! All range-initializer temporaries live across the loop.
void iterate_temporaries() {
    for (int v : make_box().get_items()) {
        (void)v;
    }
}
```

In C++11 through C++20, `make_box().get_items()` extended nothing because `__range` bound to the `const std::vector<int>&` returned by `get_items()`, leaving the outer `RangeBox` temporary to destruct immediately. C++23 paper **P2718R0** (`[stmt.ranged]`) changed the specification so that **all temporaries created inside the range-initializer expression** remain alive until the entire range-based `for` loop completes (and are destroyed in reverse order after the loop exits). Until your whole toolchain targets C++23 or newer, binding `auto box = make_box();` into a named variable before the loop remains the safest portable habit.

## What to remember

- `T&` binds only mutable lvalues, `T&&` binds only mutable rvalues, and `const T&` binds everything—including convertible types that materialize hidden temporaries.
- Direct reference binding extends a temporary (or whole object containing a bound data member or aggregate reference field) to the reference's scope.
- Lifetime extension stops cold at function calls (`std::string_view`, `.front()`, `identity()`), constructor initializer lists, `return` statements, and `new` expressions.
- C++23 (P2718R0) extends all temporaries in a range-based `for` initializer across the entire loop, fixing the classic `for (x : make().get_items())` dangling bug.

## Concept Map Outline

- **References and temporaries:** Reference initialization governs what expressions bind, when temporaries materialize, and how long they survive.
  - **Reference binding rules:** Four reference signatures accept distinct combinations of lvalues, rvalues, and constness.
    - **Non-const lvalue T&:** Binds exclusively to non-const lvalues and rejects temporaries or const objects.
    - **Rvalue reference T&&:** Binds exclusively to non-const xvalues and prvalues to enable resource stealing.
    - **Universal const T&:** Binds to lvalues, rvalues, and implicitly convertible expressions of different types.
  - **Implicit conversion temporaries:** Binding const T& across incompatible types materializes a fresh unrelated temporary object.
    - **Type mismatch copy:** Binding const int& to a double creates a separate int temporary unaffected by later writes.
    - **C++23 detection traits:** reference_constructs_from_temporary and reference_converts_from_temporary catch dangling binds.
  - **Direct lifetime extension:** Binding a local reference directly to a temporary extends its lifetime to that scope.
    - **Full-expression baseline:** Unextended temporaries destruct at the end of the enclosing full-expression in reverse order.
    - **Subobject and aggregate:** Binding a temporary's data member or aggregate reference field extends the whole temporary.
  - **Where extension stops:** Syntactic indirection through calls or constructors cancels temporary lifetime extension.
    - **Function call return:** Passing a temporary through an identity function or accessor lets it die at the semicolon.
    - **Constructor member init:** Binding a temporary to a reference member inside a constructor always dangles after construction.
    - **Return and new expressions:** Temporaries bound inside return statements or new expressions never extend past their context.
  - **Range-for and P2718R0:** C++23 closes the classic chained-temporary dangling loophole inside range-based for loops.
    - **Pre-C++23 __range cliff:** Chaining a member accessor in C++11 through C++20 left the outer temporary dead before iteration.
    - **C++23 loop-wide lifetime:** P2718R0 extends every temporary in the range-initializer expression until the loop ends.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.init.ref])

Which reference parameter type refuses to bind to `const Widget cw;` while accepting `Widget{}`?

A. const Widget&
B. Widget&&
C. const Widget&&
D. Widget&

**Answer (B):** Widget&&

**Why:** Widget&& binds only non-const rvalues (xvalues and prvalues like Widget{}), rejecting lvalues such as cw. const Widget& and const Widget&& accept const rvalues (though const Widget& also accepts cw), while Widget& rejects both.

### Question 2 [warmup] ([dcl.init.ref], [class.temporary])

What value does `r` observe after `d = 9.5;` runs in this snippet?

```cpp
double d = 3.75;
const int& r = d;
d = 9.5;
```

A. 3, because r bound to a temporary int{3} created by converting d rather than aliasing d
B. 9, because r aliases d and truncates its updated value on read
C. Compilation error: const int& cannot bind to a double
D. Undefined behavior due to strict aliasing between int and double

**Answer (A):** 3, because r bound to a temporary int{3} created by converting d rather than aliasing d

**Why:** Because int and double are not reference-related, binding const int& to double d implicitly converts d into a fresh temporary int{3} whose lifetime is extended to r. Subsequent writes to d never affect that hidden temporary.

### Question 3 [tricky] ([class.temporary])

In which snippet does `r` (or `h.ref`) remain valid rather than dangling immediately after the semicolon?

```cpp
struct Pair { int first; int second; };
Pair make_pair() { return {1, 2}; }
const int& id(const int& x) { return x; }
struct Holder {
    const int& ref;
    Holder(const int& x) : ref(x) {}
};
```

A. const int& r = id(10);
B. Holder h(10);
C. const int& r = make_pair().first;
D. std::string_view sv = std::string("abc");

**Answer (C):** const int& r = make_pair().first;

**Why:** Binding a reference directly to a non-static data member subobject of a temporary (make_pair().first) extends the entire temporary Pair object's lifetime to r. Passing through id(), storing via a non-aggregate constructor Holder, or constructing std::string_view stops lifetime extension.

### Question 4 [tricky] ([stmt.ranged], [class.temporary])

In C++17 and C++20 (before C++23 P2718R0), what happens in `for (int x : make_box().get_vec())` when `get_vec()` returns `const std::vector<int>&`?

```cpp
struct Box {
    std::vector<int> vec{1, 2, 3};
    const std::vector<int>& get_vec() const { return vec; }
};
Box make_box();
```

A. Well-defined in all C++ versions because range-for extends every temporary in the header
B. Well-defined only if int x is changed to const auto& x
C. Compile error in C++17/C++20
D. Undefined behavior in C++17/C++20 because auto&& __range binds to get_vec()'s return reference, letting the Box temporary destruct before the loop starts

**Answer (D):** Undefined behavior in C++17/C++20 because auto&& __range binds to get_vec()'s return reference, letting the Box temporary destruct before the loop starts

**Why:** In C++11 through C++20, range-for initializes auto&& __range = make_box().get_vec();. Because get_vec() is a member function call, __range does not extend the Box temporary, which is destroyed at the semicolon before iteration begins. C++23 P2718R0 fixed this in [stmt.ranged].

### Question 5 [standardese] ([meta.unary.prop], [dcl.init.ref])

What do `std::reference_converts_from_temporary_v<const std::string&, std::string>` and `std::reference_converts_from_temporary_v<const std::string&, std::string&>` evaluate to in C++23?

A. false and false, because both have the same underlying type std::string
B. true and false, because std::string (unqualified) models a prvalue that materializes a temporary, whereas std::string& is an lvalue that binds directly
C. false and true
D. true and true

**Answer (B):** true and false, because std::string (unqualified) models a prvalue that materializes a temporary, whereas std::string& is an lvalue that binds directly

**Why:** In <type_traits> ([meta.unary.prop]), the second template argument U models an expression of type declval<U>(). When U is std::string (non-reference), declval<std::string>() is an rvalue, so binding const std::string& creates/materializes a temporary (true). When U is std::string&, declval<std::string&>() is an lvalue and binds directly (false).

### Question 6 [standardese] ([class.temporary])

When an aggregate struct `struct Agg { const std::string& s; };` is aggregate-initialized via `Agg a{"hello"};`, what is the lifetime of the materialized `std::string` temporary?

```cpp
struct Agg { const std::string& s; };
Agg a{"hello"};
```

A. It is destroyed at the semicolon of Agg a{"hello"};, leaving a.s dangling
B. It is extended to match the lifetime of a (the enclosing aggregate object)
C. It lives in static storage until program exit
D. Aggregate initialization of a reference member from a string literal is ill-formed

**Answer (B):** It is extended to match the lifetime of a (the enclosing aggregate object)

**Why:** Under [class.temporary]/6.1, a temporary bound to a reference element of an aggregate via aggregate initialization has its lifetime extended to match the lifetime of the aggregate object a itself—unlike a user-declared constructor's mem-initializer, which does not extend lifetime.

---

# Track: Expressions and functions

Evaluation order guarantees, compile-time execution, closure types and overload resolution.

# Evaluation Order, Sequencing & Undefined Side Effects

> Separate operator precedence from evaluation order, read C++17's tightened sequencing guarantees, and avoid unsequenced undefined behavior.

- **Source:** C++ Atlas (https://cppatlas.com/topics/evaluation-order)
- **Track:** Expressions and functions
- **Estimated reading time:** 7 minutes
- **ISO C++ clauses:** [intro.execution] (https://eel.is/c++draft/intro.execution), [expr.call] (https://eel.is/c++draft/expr.call), [expr.ass] (https://eel.is/c++draft/expr.ass), [expr.log.and] (https://eel.is/c++draft/expr.log.and), [expr.cond] (https://eel.is/c++draft/expr.cond), [expr.comma] (https://eel.is/c++draft/expr.comma)
- **cppreference links:** [Order of evaluation](https://en.cppreference.com/w/cpp/language/eval_order), [Operator Precedence](https://en.cppreference.com/w/cpp/language/operator_precedence), [Increment/decrement operators](https://en.cppreference.com/w/cpp/language/operator_incdec), [Logical operators](https://en.cppreference.com/w/cpp/language/operator_logical)
- **Prerequisites:** value-categories

Many C++ bugs start with a simple confusion: reading an expression's operator precedence as if it were a runtime schedule. When you write `f() + g() * h()`, operator precedence forces `*` to bind tighter than `+`, grouping the expression as `f() + (g() * h())`. Precedence builds the syntax tree, not the execution timeline. The compiler is completely free to evaluate `f()` before `g()`, after `h()`, or between them, because `+` and `*` impose no ordering constraint between their subexpressions.

> **Mental model.** Precedence and associativity decide *which operands belong to which operator*; sequencing decides *when side effects and value computations happen in time*. Two expressions can share the exact same parse tree on every compiler while running their leaf calls in opposite orders under different optimization flags.

## Sequenced-before, unsequenced, and indeterminately sequenced

To talk precisely about time inside a single thread, the C++ standard defines every evaluation as two steps: **value computation** (producing the result) and **initiation of side effects** (modifying an object, reading a `volatile` glvalue, or invoking I/O). Between any two evaluations `A` and `B`, `[intro.execution]` defines exactly three possible ordering relationships:

1. **Sequenced before.** Both the value computation and every side effect of `A` finish completely before `B` begins. Semicolons (`;`), full-expression boundaries, and specific operators establish this strict edge.
2. **Indeterminately sequenced.** Either `A` is sequenced before `B`, or `B` is sequenced before `A`, and the compiler does not have to tell you which—even across different call sites in the same binary. Crucially, `A` and `B` **cannot overlap** or interleave instructions.
3. **Unsequenced.** `A` and `B` may execute in any order and may interleave step-by-step on the abstract machine.

That third category is where undefined behavior lives. Under `[intro.execution]/10`, if a side effect on a scalar object is **unsequenced** relative to either a different side effect on the same scalar object or a value computation using the value of that same scalar object, the behavior is **undefined**—not unspecified, not implementation-defined, completely undefined.

> **Standardese.** "If a side effect on a memory location is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent, the behavior is undefined." — `[intro.execution]`

```cpp
int f();
int g();
int h();

void demo(int i) {
    // Parse tree is f() + (g() * h()), yet f(), g(), and h()
    // are indeterminately sequenced relative to one another.
    int total = f() + g() * h();

    // Undefined behavior: two unsequenced mutations/reads of scalar 'i'.
    // int bad = i++ + ++i;
    // int also_bad = i + i++;
    (void)total;
    (void)i;
}
```

## What C++17 guaranteed—and what it did not

Before C++17, idioms as ordinary as `std::cout << a() << b()` or `map[key] = build()` carried subtle traps because almost every binary operator left its operands unsequenced. C++17 (via P0145R3) tightened the abstract machine so postfix chains, shifts, and assignments have predictable order, while intentionally leaving arithmetic and comparison operators unsequenced so optimizers can keep scheduling registers freely.

| Expression form | Sequencing rule since C++17 | Notes |
| --- | --- | --- |
| `a.b`, `a->b`, `a->*b`, `a.*b` | `a` before `b` | Member access proceeds left-to-right |
| `a[b]` | `a` before `b` | Applies to built-in and overloaded `operator[]` |
| `a << b`, `a >> b` | `a` before `b` | Stream chaining `cout << f() << g()` calls `f()` first |
| `a = b`, `a @= b` | `b` before `a` | Right operand completes before left operand |
| `a(b1, b2, ...)` | `a` before all `bi`; `bi` indeterminately sequenced | Arguments cannot interleave each other |
| `{e1, e2, ...}` | `e1` before `e2` before `...` | Braced-init-lists evaluate strictly left-to-right |
| `a + b`, `a * b`, `a < b` | Unsequenced (function calls indeterminately sequenced) | Never mutate and read the same scalar across sides |

Look closely at the assignment row in that summary. Both built-in assignments and operator-syntax assignments (`a = b`, `a += b`) evaluate their **right-hand operand completely before their left-hand operand** (`[expr.ass]/1` combined with `[over.match.oper]/2`). Even in `v[i] = i++;`, C++17 sequences `i++` (computing `0` and incrementing `i` to `1`) before evaluating `v[i]`, storing `0` into `v[1]`. That was undefined behavior in C++14; it is well-defined in C++17 and later, though still hostile to human readers and worth splitting into two clear statements.

```cpp
#include <iostream>

struct Sink {
    Sink& operator=(const Sink&) { return *this; }
};

Sink& pick_target(Sink& s) {
    std::cout << "lhs ";
    return s;
}

Sink build_value() {
    std::cout << "rhs ";
    return Sink{};
}

int step(const char* tag, int value) {
    std::cout << tag << ' ';
    return value;
}

void sequencing_demo() {
    Sink target;
    pick_target(target) = build_value(); // Prints: rhs lhs

    std::cout << step("first", 1) << step("second", 2) << '\n'; // Prints: first 1second 2

    int ordered[] = { step("one", 1), step("two", 2), step("three", 3) };
    (void)ordered;
}
```

## Function arguments and the smart-pointer classic

Function-call syntax `f(a1, a2, ...)` obeys two distinct rules. First, the postfix expression `f` itself—which might compute a function pointer or callable object—is sequenced before every argument expression and before every default argument (`[expr.call]/7`). Second, the argument expressions `a1`, `a2`, and so on are **indeterminately sequenced** relative to one another, rather than unsequenced.

That distinction solved a notorious pre-C++17 memory leak:

```cpp
#include <memory>

struct Widget { explicit Widget(int) {} };
int compute_or_throw();
void consume(std::shared_ptr<Widget>, int);

void call_site() {
    // Pre-C++17: compiler could run (1) new Widget{1}, (2) compute_or_throw(),
    // and only then (3) shared_ptr ctor — leaking Widget if step 2 threw!
    // C++17+: argument 1 and argument 2 cannot interleave, closing the leak.
    consume(std::shared_ptr<Widget>(new Widget{1}), compute_or_throw());

    // Still cleaner and avoids a separate control-block allocation:
    consume(std::make_shared<Widget>(1), compute_or_throw());
}
```

Notice what C++17 did *not* change: `compute_or_throw()` is still allowed to run before `new Widget{1}`, or after `std::shared_ptr<Widget>(new Widget{1})` finishes constructing. Only interleaving the steps inside one argument with the steps of another argument was outlawed. Also remember that parameter initialization completes for every argument before the function body begins executing, and parameter destruction order at the end of the call is implementation-defined (though commonly right-to-left on the Itanium ABI and left-to-right on MSVC).

## Short-circuiting, commas, and overloaded operators

Four built-in operators enforce strict left-to-right control flow: logical AND (`a && b`), logical OR (`a || b`), the ternary conditional (`a ? b : c`), and the comma operator (`a, b`). For built-in `&&` and `||`, `a` is sequenced before `b`, and `b` is never evaluated at all if `a` settles the boolean outcome. Similarly, `a ? b : c` completes `a` and all of its side effects before starting whichever single branch (`b` or `c`) is selected. Built-in `a, b` evaluates `a`, discards its result, and sequences `a` before `b`.

> **Pitfall.** Overloading `operator&&`, `operator||`, or `operator,` breaks short-circuiting. While C++17 preserves left-before-right operand sequencing in `[over.match.oper]/2`, user-defined `operator&&` is still a function call whose parameters must both be initialized before entry—so the right-hand operand always evaluates, even when the left-hand operand is logically false.

Finally, keep the **comma operator** separate from **comma separators**. The commas inside `foo(a(), b())` separate function arguments and leave their order unspecified (indeterminately sequenced). The commas inside `{a(), b()}` separate braced-initializer clauses, which *are* guaranteed left-to-right (`[dcl.init.list]/4`). Only `(a(), b())`—wrapped in parentheses as a single expression—invokes the comma operator itself.

## What to remember

- **Precedence is syntax, sequencing is time.** Operators like `+` and `*` bind operands into a tree without ordering their subexpressions.
- **Unsequenced scalar conflicts are UB.** Never read or write a scalar object more than once across unsequenced subexpressions such as `i++ + ++i`.
- **C++17 fixed chains, shifts, and assignments.** Left-to-right holds for `.`, `->`, `[]`, `<<`, `>>`, and `{...}`, while `=` and `@=` evaluate right-before-left.
- **Function arguments still have no fixed order.** Arguments cannot interleave after C++17, yet any argument may still finish before its siblings start.
- **Never overload `&&`, `||`, or `,`.** Custom overloads evaluate both operands eagerly and defeat the short-circuit contract readers expect.

## Concept Map Outline

- **Evaluation Order:** C++ separates syntax grouping from runtime sequencing and defines strict rules for side-effect visibility.
  - **Precedence vs Ordering:** Syntax trees bind operands to operators without dictating which subexpression runs first.
    - **Precedence builds parse tree:** Higher-precedence operators claim neighboring operands before lower-precedence operators.
    - **Associativity groups ties:** Left or right associativity resolves equal-precedence chains such as a - b - c.
    - **Order picks runtime schedule:** The optimizer schedules subexpressions freely unless a sequencing edge constrains them.
  - **Sequencing Relations:** Every pair of single-thread evaluations is sequenced, indeterminately sequenced, or unsequenced.
    - **Sequenced before:** Value computation and all side effects of the first complete before the second starts.
    - **Indeterminately sequenced:** Either evaluation finishes before the other without interleaving instructions.
    - **Unsequenced conflicts:** Two unsequenced accesses to one scalar where at least one writes cause undefined behavior.
  - **C++17 Guarantees:** P0145R3 ordered postfix chains, shifts, assignments, and separated function arguments.
    - **Postfix and subscript left-first:** Member access and array indexing always finish evaluating the left object first.
    - **Shifts evaluate left-to-right:** Chained stream insertions and bit shifts sequence the left operand before the right.
    - **Assignment right-before-left:** Simple and compound assignments evaluate the right operand completely before the left.
    - **Arguments cannot interleave:** Each argument finishes without interleaving, preventing nested smart-pointer leaks.
  - **Short-Circuit & Lists:** Control-flow operators and braced initializers enforce deterministic left-to-right steps.
    - **Built-in logical operators:** Built-in && and || sequence left before right and skip the right when already decided.
    - **Ternary conditional:** The condition and its side effects complete before the single chosen branch evaluates.
    - **Braced initializer lists:** Clauses inside curly braces always evaluate strictly left-to-right.
  - **Overload Traps:** User-defined operators alter function-call timing and disable short-circuiting.
    - **Overloaded && evaluates eagerly:** Custom operator&& is a function call, so both operands evaluate even when the left is false.
    - **Overloaded ops keep order:** Operator syntax preserves the built-in operand order while function notation does not.

## Standardese Quiz Questions

### Question 1 [warmup] ([intro.execution], [expr.mul])

In `int x = a() + b() * c();` (C++23), what does operator precedence guarantee about runtime execution?

```cpp
int x = a() + b() * c();
```

A. `b()` and `c()` must both execute before `a()` executes.
B. `a()` must execute first because reading happens left-to-right.
C. The result of `b() * c()` is added to `a()`, while `a()`, `b()`, and `c()` may run in any order.
D. The expression is undefined behavior unless parentheses are added around `b() * c()`.

**Answer (C):** The result of `b() * c()` is added to `a()`, while `a()`, `b()`, and `c()` may run in any order.

**Why:** Operator precedence makes `*` bind tighter than `+`, building the syntax tree `a() + (b() * c())`. It does not schedule the three function calls: `a()`, `b()`, and `c()` are indeterminately sequenced and may run in any non-overlapping order.

### Question 2 [warmup] ([expr.shift], [over.match.oper])

Since C++17, what does `std::cout << first() << second() << '\n';` guarantee?

```cpp
int first();
int second();
std::cout << first() << second() << '\n';
```

A. `first()` is sequenced before `second()`, regardless of optimization level.
B. `first()` and `second()` are still indeterminately sequenced because `operator<<` is overloaded.
C. `second()` runs before `first()` because arguments bind right-to-left.
D. The behavior is unspecified unless `first()` and `second()` are `noexcept`.

**Answer (A):** `first()` is sequenced before `second()`, regardless of optimization level.

**Why:** C++17 made `E1 << E2` sequence `E1` before `E2`, and `[over.match.oper]/2` applies that built-in sequencing rule to overloaded operator syntax as well. Therefore `std::cout << first()` completes before `second()` starts.

### Question 3 [tricky] ([expr.log.and], [over.match.oper])

Consider a type `Flag` with an overloaded `operator&&`. When evaluating `left() && right()`, what happens if `left()` returns `Flag{false}`?

```cpp
struct Flag {
    bool ok;
    friend bool operator&&(Flag a, Flag b) { return a.ok && b.ok; }
};
Flag left();
Flag right();
bool r = left() && right();
```

A. `right()` is skipped due to short-circuit evaluation.
B. `right()` still executes because overloaded `operator&&` is a function call without short-circuiting.
C. `right()` may execute before `left()` because function arguments are unsequenced.
D. The program is ill-formed because overloading `operator&&` is forbidden since C++17.

**Answer (B):** `right()` still executes because overloaded `operator&&` is a function call without short-circuiting.

**Why:** Overloaded `operator&&` is dispatched as a regular function call, so both argument expressions (`left()` and `right()`) must be evaluated before the function body starts—short-circuiting is lost. Meanwhile, `[over.match.oper]/2` still sequences `left()` before `right()`.

### Question 4 [tricky] ([expr.call], [intro.execution])

In C++23, what is true about `consume(std::shared_ptr<Widget>(new Widget{1}), compute());` if `compute()` can throw?

```cpp
struct Widget { explicit Widget(int); };
int compute();
void consume(std::shared_ptr<Widget>, int);

consume(std::shared_ptr<Widget>(new Widget{1}), compute());
```

A. It can leak `Widget` if `compute()` runs between `new Widget{1}` and the `shared_ptr` constructor.
B. Argument 1 is guaranteed to finish before `compute()` is called.
C. `compute()` is guaranteed to run before `new Widget{1}`.
D. No leak occurs because argument evaluations cannot interleave, though `compute()` and argument 1 may run in either order.

**Answer (D):** No leak occurs because argument evaluations cannot interleave, though `compute()` and argument 1 may run in either order.

**Why:** Since C++17, function argument expressions are indeterminately sequenced rather than unsequenced (`[expr.call]/7`). Neither argument can interleave with the other—preventing the pre-C++17 leak—but the compiler may still evaluate argument 1 first or `compute()` first.

### Question 5 [standardese] ([expr.ass], [over.match.oper])

In C++23, what does `pick_lhs(a) = make_rhs();` print when `Target` defines `operator=`?

```cpp
struct Target {
    Target& operator=(const Target&) {
        std::cout << "assign ";
        return *this;
    }
};
Target& pick_lhs(Target& t) { std::cout << "lhs "; return t; }
Target make_rhs() { std::cout << "rhs "; return Target{}; }

Target a;
pick_lhs(a) = make_rhs();
```

A. `lhs rhs assign ` because member calls evaluate their left object before arguments.
B. `rhs lhs assign ` because operator-syntax assignment sequences the right operand before the left.
C. Either `lhs rhs assign ` or `rhs lhs assign ` because the order is unspecified.
D. Undefined behavior because `pick_lhs` and `make_rhs` are unsequenced.

**Answer (B):** `rhs lhs assign ` because operator-syntax assignment sequences the right operand before the left.

**Why:** In `[expr.ass]/1`, the right operand of an assignment is sequenced before the left operand. Under `[over.match.oper]/2`, expressions written with operator syntax (`pick_lhs(a) = make_rhs()`) preserve the built-in operator's operand sequencing rather than member-call order.

### Question 6 [standardese] ([expr.ass], [intro.execution])

Under C++23 rules, what is the behavior of `int i = 0; int v[2] = {10, 20}; v[i] = i++;`?

```cpp
int i = 0;
int v[2] = {10, 20};
v[i] = i++;
```

A. Well-defined: sets `v[1] = 0` and leaves `i == 1`.
B. Undefined behavior because `i` is modified and read unsequenced.
C. Well-defined: sets `v[0] = 0` and leaves `i == 1`.
D. Unspecified whether `v[0]` or `v[1]` receives `0`.

**Answer (A):** Well-defined: sets `v[1] = 0` and leaves `i == 1`.

**Why:** While `v[i] = i++;` was undefined behavior in C++14, C++17 `[expr.ass]/1` sequenced the right operand (`i++`, yielding `0` and incrementing `i` to `1`) completely before the left operand (`v[i]`). Thus `v[1]` is assigned `0` and `i` becomes `1`.

# Constant Expressions: constexpr, consteval & constinit

> Distinguish core constant expressions from constant-evaluated contexts, choose cleanly between constexpr, consteval, and constinit, and branch safely with if consteval.

- **Source:** C++ Atlas (https://cppatlas.com/topics/constant-expressions)
- **Track:** Expressions and functions
- **Estimated reading time:** 8 minutes
- **ISO C++ clauses:** [expr.const] (https://eel.is/c++draft/expr.const), [dcl.constexpr] (https://eel.is/c++draft/dcl.constexpr), [dcl.consteval] (https://eel.is/c++draft/dcl.consteval), [dcl.constinit] (https://eel.is/c++draft/dcl.constinit), [stmt.if] (https://eel.is/c++draft/stmt.if), [meta.const.eval] (https://eel.is/c++draft/meta.const.eval)
- **cppreference links:** [Constant expressions](https://en.cppreference.com/w/cpp/language/constant_expression), [constexpr specifier](https://en.cppreference.com/w/cpp/language/constexpr), [consteval specifier](https://en.cppreference.com/w/cpp/language/consteval), [constinit specifier](https://en.cppreference.com/w/cpp/language/constinit), [if statement](https://en.cppreference.com/w/cpp/language/if)
- **Prerequisites:** evaluation-order, initialization-forms

When developers hear "compile-time evaluation," they often picture an aggressive optimizer folding arithmetic constants at `-O2`. In C++, **constant expressions** are something far stronger: a formal part of the language rules defined in `[expr.const]` that governs what the compiler *must* evaluate during translation—even at `-O0`—and when an evaluation error becomes a hard diagnostic.

> **Mental model.** `constexpr` on a function means "permitted in constant evaluation," not "forced at compile time." On a variable, `constexpr` means both "compile-time initialized" and `const`. When you want compile-time initialization *without* `const`, reach for `constinit`; when you want compile-time execution *mandatorily*, reach for `consteval`.

## What makes an expression constant

The standard splits the idea into two layers. First, an expression is a **core constant expression** unless evaluating it runs into a forbidden runtime operation under `[expr.const]/5`. Disqualified operations include calling a non-`constexpr` function, reading an uninitialized scalar or `volatile` glvalue, performing `reinterpret_cast`, throwing an uncaught exception, or triggering **any undefined behavior**.

Second, to serve as a full **constant expression** (for instance, to initialize a `constexpr` variable or size a `std::array`), the result cannot dangle: it cannot point or refer to an automatic local variable or to heap memory that has not been freed before evaluation ends.

Just as important is *when* the compiler is required to evaluate one. The standard calls those places **manifestly constant-evaluated contexts**:

- `static_assert` conditions and `if constexpr (...)` predicates
- Non-type template arguments and array bounds
- Initializers of `constexpr` and `constinit` variables
- Invocations of `consteval` functions
- `const` integral or enumeration variables whose initializers happen to be constant expressions

Outside those contexts, calling a `constexpr` function with literal arguments might evaluate at compile time as an optimization—or might run at runtime under `-O0`.

## constexpr vs. consteval vs. constinit

Mixing up these three specifiers is easy because they share a prefix, yet each solves a distinct problem.

| Specifier | Applies to | Evaluation timing | Resulting object mutable? | Usable with runtime inputs? |
| --- | --- | --- | --- | --- |
| `constexpr` (variable) | Variables (and static data members) | Must be constant-initialized | No (implicitly `const`) | N/A |
| `constexpr` (function) | Functions and constructors | Compile-time *or* runtime | N/A | Yes |
| `consteval` | Functions and constructors | **Always** compile-time | N/A | No (compile error) |
| `constinit` | Static or `thread_local` variables | Must be constant-initialized | **Yes** (unless also `const`) | N/A |

Notice two details in that comparison that routinely trip people up. First, `constexpr` on a function signature never makes the return type `const` (unlike `constexpr` on a variable, where `constexpr int* p` means `int* const p`—top-level `const`!). Second, `constinit` solves the **static initialization order fiasco** for mutable globals and `thread_local` caches: if the initializer is not a valid constant expression, compilation fails immediately instead of silently falling back to dynamic initialization before `main`.

```cpp
consteval int square_now(int n) {
    return n * n;
}

constexpr int square_anytime(int n) {
    return n * n;
}

// Guaranteed static initialization, yet still mutable at runtime.
constinit int global_hits = square_now(4);

// Compile-time constant and implicitly const.
constexpr int table_size = square_anytime(8);
static_assert(table_size == 64);

int runtime_demo(int user_input) {
    global_hits += 1;                        // Legal: constinit is not const
    // int bad = square_now(user_input);     // Error: user_input is not constant
    return square_anytime(user_input);       // Legal: runs at runtime
}
```

## Transient allocation and C++20/23 expansions

Since C++20, constant evaluation supports `new` and `delete`, which enables `constexpr` `std::vector` and `std::string`. There is one strict boundary rule: **transient allocation**. Any dynamic memory allocated during a constant evaluation must be deallocated before that constant evaluation returns its final value (`[expr.const]/5`).

You can build and sort a `std::vector<int>` inside a `constexpr` or `consteval` helper, extract a scalar summary, a fixed `std::array`, or a count, and let the vector's destructor free its buffer before leaving the compile-time evaluator. What you *cannot* do is declare `constexpr std::vector<int> v{1, 2, 3};` at namespace scope, because its heap buffer would attempt to survive past the end of constant evaluation.

```cpp
#include <array>
#include <cstddef>
#include <vector>

consteval int triangular_sum(int n) {
    std::vector<int> scratch;
    for (int i = 1; i <= n; ++i) {
        scratch.push_back(i);
    }
    int sum = 0;
    for (int x : scratch) {
        sum += x;
    }
    return sum; // scratch is destroyed and freed here: valid transient allocation
}

static_assert(triangular_sum(6) == 21);

// To persist compile-time data into the binary, copy into std::array:
consteval std::array<int, 4> make_squares() {
    std::vector<int> tmp{1, 2, 3, 4};
    std::array<int, 4> out{};
    for (std::size_t i = 0; i < out.size(); ++i) {
        out[i] = tmp[i] * tmp[i];
    }
    return out;
}

constexpr auto squares = make_squares();
static_assert(squares[3] == 16);
```

C++23 further widened what can sit inside a `constexpr` function: `static constexpr` variables are now permitted locally, `goto` restrictions eased, and a `constexpr` function no longer causes an error just because *no* valid constant-expression instantiation exists yet (P2448R2).

## Dual-path code with if consteval (C++23)

Sometimes a function needs two implementations: a portable pure-C++ algorithm for compile-time evaluation and a SIMD intrinsic or assembly path at runtime. C++20 introduced `std::is_constant_evaluated()` in `<type_traits>` for that split, and C++23 added a dedicated statement syntax: `if consteval { ... } else { ... }` (notice: **no parentheses** around a condition).

> **Pitfall.** Never write `if constexpr (std::is_constant_evaluated())`. Because the predicate of `if constexpr` is itself a manifestly constant-evaluated context, `std::is_constant_evaluated()` unconditionally evaluates to `true` there—silently discarding your runtime branch even when the outer function is called at runtime.

C++23 `if consteval` eliminates that mistake by syntax alone and adds one capability `if (std::is_constant_evaluated())` lacks: inside the `if consteval` branch, the compiler puts you inside an immediate-function context, allowing direct calls to `consteval` functions using the enclosing function's parameters.

```cpp
#include <type_traits>

consteval int compile_time_hash(int x) { return x * 2654435761u; }
int runtime_crc(int x) { return x ^ 0x5555; }

constexpr int compute_tag(int x) {
    if consteval {
        // Immediate context: calling a consteval function with 'x' is legal here!
        return compile_time_hash(x);
    } else {
        return runtime_crc(x);
    }
}

constexpr int c_tag = compute_tag(7); // Takes the `if consteval` branch

int runtime_tag(int dynamic_x) {
    return compute_tag(dynamic_x);    // Takes the `else` branch
}
```

## Undefined behavior is forbidden at compile time

One underappreciated gift of `constexpr` and `consteval` is that the constant evaluator acts as a built-in undefined-behavior detector. Outside constant evaluation, signed integer overflow, shifting by a negative count, dereferencing a null pointer, reading past the end of an array, or reading an inactive union member can slip silently into compiled machine code. Inside constant evaluation, `[expr.const]/5` rejects *every* core-language undefined behavior with a compile-time diagnostic explaining which rule failed.

> **Standardese.** "An expression `E` is a core constant expression unless the evaluation of `E`, following the rules of the abstract machine, would evaluate one of the following: ... an operation that would have undefined behavior as specified in [intro] through [cpp]." — `[expr.const]`

## What to remember

- **Core constant expressions reject UB.** Any undefined behavior during evaluation turns a constant expression into a guaranteed compile error.
- **Keep the three keywords distinct.** `constexpr` allows compile-time evaluation (and adds `const` to variables), `consteval` requires compile-time evaluation, and `constinit` enforces static initialization on mutable static/thread-local objects.
- **Dynamic memory works if it stays local.** Compile-time `std::vector` and `std::string` allocations are legal as long as they are freed before evaluation returns.
- **Prefer `if consteval` in C++23.** It avoids the `if constexpr (std::is_constant_evaluated())` bug and unlocks calling `consteval` helpers directly.
- **Function `constexpr` is not return `const`.** Always read `constexpr` on a function as an evaluation capability, not a qualifier on its return type.

## Concept Map Outline

- **Constant Expressions:** Compile-time evaluation obeys strict abstract-machine rules governed by constexpr, consteval, and constinit.
  - **Core Constant Rules:** Core constant expressions disallow runtime-only operations, dangling outputs, and all undefined behavior.
    - **No undefined behavior:** Signed overflow, out-of-bounds reads, and inactive union access fail to compile.
    - **No dangling results:** Final constant values cannot point to local stack slots or unfreed heap storage.
    - **Manifestly constant contexts:** static_assert, template arguments, constexpr vars, and consteval calls force compile-time evaluation.
  - **Three Specifiers:** Each keyword controls timing and mutability differently across variables and functions.
    - **constexpr allows compile time:** constexpr functions run at compile time or runtime; constexpr variables are implicitly const.
    - **consteval forces compile time:** Immediate functions execute solely during translation and reject runtime arguments.
    - **constinit enforces static init:** constinit prevents dynamic initialization order bugs while keeping static or thread-local variables mutable.
  - **Transient Allocation:** C++20 allows dynamic allocations inside constant evaluation provided they are freed before returning.
    - **Compile-time new and delete:** Dynamic allocations and deallocations succeed inside constexpr evaluation contexts.
    - **Allocations cannot escape:** Heap pointers from constant evaluation cannot persist into runtime global objects.
    - **Copy to std::array:** Extract results from temporary std::vector buffers into fixed arrays to persist data.
  - **Dual-Path Branching:** Select portable compile-time logic or optimized runtime code within one constexpr function.
    - **std::is_constant_evaluated:** Returns true inside a plain if statement only during constant evaluation.
    - **if constexpr trap:** Wrapping std::is_constant_evaluated inside if constexpr always evaluates to true.
    - **C++23 if consteval:** Enters an immediate context that avoids the trap and permits calling consteval helpers.
  - **Subtle Boundaries:** Specifier placement and function pointers follow rules distinct from ordinary runtime code.
    - **Pointer top-level const:** constexpr on a pointer variable makes the pointer itself const rather than the pointee.
    - **Immediate function pointers:** Taking the runtime address of a consteval function is ill-formed outside constant evaluation.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.constexpr], [dcl.consteval])

Given `constexpr int a(int x) { return x + 1; }` and `consteval int b(int x) { return x + 1; }`, what happens when `main` calls both with a non-constant local `int n = 5;`?

```cpp
constexpr int a(int x) { return x + 1; }
consteval int b(int x) { return x + 1; }

int main() {
    int n = 5;
    int r1 = a(n);
    int r2 = b(n);
    return r1 + r2;
}
```

A. Both `a(n)` and `b(n)` compile and run at runtime.
B. `a(n)` compiles and runs at runtime, while `b(n)` is a compile error.
C. `a(n)` is a compile error because `n` is not constant, while `b(n)` compiles.
D. Both `a(n)` and `b(n)` fail to compile because `n` is not `constexpr`.

**Answer (B):** `a(n)` compiles and runs at runtime, while `b(n)` is a compile error.

**Why:** A `constexpr` function may execute either at compile time or at runtime depending on the call context, so `a(n)` runs cleanly at runtime. A `consteval` function is an immediate function (`[dcl.consteval]`) whose every evaluation must be a compile-time constant expression, so `b(n)` is ill-formed.

### Question 2 [warmup] ([dcl.constinit], [dcl.constexpr])

When should you declare a namespace-scope variable `constinit` instead of `constexpr`?

A. When the variable is a local automatic variable inside a function.
B. When the initializer depends on runtime user input.
C. When you want the variable to have internal linkage automatically.
D. When you want guaranteed static initialization to avoid initialization-order bugs while still mutating the variable at runtime.

**Answer (D):** When you want guaranteed static initialization to avoid initialization-order bugs while still mutating the variable at runtime.

**Why:** `constinit` (`[dcl.constinit]`) requires constant initialization for a variable with static or thread storage duration—preventing dynamic initialization order bugs—without making the variable `const`. `constexpr` makes the variable implicitly `const`.

### Question 3 [tricky] ([stmt.if], [meta.const.eval])

What is the bug in `compute(int x)` below when invoked with a runtime integer `n`?

```cpp
constexpr int compute(int x) {
    if constexpr (std::is_constant_evaluated()) {
        return x * 2;
    } else {
        return x + 1;
    }
}
```

A. `std::is_constant_evaluated()` cannot be called in an `if constexpr` condition.
B. It returns `x + 1` at runtime and `x * 2` at compile time.
C. The `if constexpr` condition is manifestly constant-evaluated, so `std::is_constant_evaluated()` is always `true` and the `else` branch is discarded.
D. The code fails to compile because `x` is not a template parameter.

**Answer (C):** The `if constexpr` condition is manifestly constant-evaluated, so `std::is_constant_evaluated()` is always `true` and the `else` branch is discarded.

**Why:** The condition of `if constexpr` is always evaluated as a constant expression (`[stmt.if]`), so `std::is_constant_evaluated()` unconditionally returns `true` there. Even when `compute(n)` is called at runtime, it executes `x * 2`. Use plain `if (std::is_constant_evaluated())` in C++20 or `if consteval` in C++23.

### Question 4 [tricky] ([expr.const])

Which declaration using `std::vector` compiles cleanly in C++23?

```cpp
consteval std::size_t vec_len() {
    std::vector<int> v{1, 2, 3};
    return v.size();
}
consteval std::vector<int> make_vec() {
    return std::vector<int>{1, 2, 3};
}
```

A. `constexpr std::size_t n = vec_len();` compiles, while `constexpr auto v = make_vec();` fails.
B. Both `constexpr std::size_t n = vec_len();` and `constexpr auto v = make_vec();` compile.
C. Neither compiles because `std::vector` allocates dynamic heap memory.
D. `constexpr auto v = make_vec();` compiles only if `v` is declared `constinit`.

**Answer (A):** `constexpr std::size_t n = vec_len();` compiles, while `constexpr auto v = make_vec();` fails.

**Why:** C++20/23 supports transient allocation (`[expr.const]/5`): compile-time `new` and `delete` are permitted inside `vec_len()` because `v` is destroyed and freed before evaluation completes. Returning `std::vector` into a `constexpr` variable attempts to retain unfreed allocation past constant evaluation, which is ill-formed.

### Question 5 [standardese] ([stmt.if], [expr.const])

Why does calling a `consteval` helper `ce(x)` compile inside `if consteval` in C++23 when it fails inside `if (std::is_constant_evaluated())`?

```cpp
consteval int ce(int v) { return v * 3; }

constexpr int f(int x) {
    if consteval {
        return ce(x);
    }
    return x;
}
```

A. `if consteval` converts the parameter `x` into a template parameter automatically.
B. The compound statement of `if consteval` is an immediate-function context, whereas an ordinary `if` block is not.
C. `std::is_constant_evaluated()` is deprecated in C++23 and forbidden with `consteval`.
D. Inside `if consteval`, `ce(x)` is silently rewritten into a runtime call.

**Answer (B):** The compound statement of `if consteval` is an immediate-function context, whereas an ordinary `if` block is not.

**Why:** Under `[stmt.if]` and `[expr.const]`, the true branch of `if consteval` places expressions in an immediate-function context, allowing calls to `consteval` functions using non-constant parameters of the enclosing `constexpr` function. A plain `if (std::is_constant_evaluated())` does not create an immediate context.

### Question 6 [standardese] ([expr.const], [dcl.constexpr])

What does the C++ standard require when evaluating a `constexpr` variable initializer triggers signed integer overflow (`INT_MAX + 1`)?

```cpp
#include <limits>
constexpr int overflow = std::numeric_limits<int>::max() + 1;
```

A. It wraps around cleanly using two's complement arithmetic.
B. It compiles with a warning and stores an unspecified value.
C. It only fails if `-Werror` or `-fsanitize=undefined` is enabled.
D. The program is ill-formed because any undefined behavior disqualifies a core constant expression.

**Answer (D):** The program is ill-formed because any undefined behavior disqualifies a core constant expression.

**Why:** `[expr.const]/5` explicitly disqualifies any evaluation that triggers undefined behavior in the abstract machine from being a core constant expression. Since `constexpr` requires a constant expression initializer, the compiler must emit a diagnostic.

# Lambdas: Closure Types, Captures & Generic Parameters

> Read every lambda as the compiler lowers it: a unique unnamed closure struct, captured data members, const-by-default operator(), and C++20/23 template and explicit-this extensions.

- **Source:** C++ Atlas (https://cppatlas.com/topics/lambdas)
- **Track:** Expressions and functions
- **Estimated reading time:** 8 minutes
- **ISO C++ clauses:** [expr.prim.lambda] (https://eel.is/c++draft/expr.prim.lambda), [expr.prim.lambda.closure] (https://eel.is/c++draft/expr.prim.lambda.closure), [expr.prim.lambda.capture] (https://eel.is/c++draft/expr.prim.lambda.capture), [expr.prim.lambda.general] (https://eel.is/c++draft/expr.prim.lambda.general)
- **cppreference links:** [Lambda expressions](https://en.cppreference.com/w/cpp/language/lambda), [The this pointer](https://en.cppreference.com/w/cpp/language/this), [Implicit conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion), [Placeholder type specifiers](https://en.cppreference.com/w/cpp/language/auto), [std::function](https://en.cppreference.com/w/cpp/utility/functional/function)
- **Prerequisites:** value-categories, type-deduction-auto-decltype

A lambda expression is syntactic sugar with remarkably transparent semantics. Whenever the compiler sees `[captures](params) { body }`, it synthesizes a fresh, unnamed non-union class—called the **closure type** (`[expr.prim.lambda.closure]`)—with one data member per capture and a public `operator()` containing your body. The lambda expression itself evaluates to a prvalue **closure object** of that type.

> **Mental model.** Never treat a lambda as an opaque heap allocation or a bare function pointer. By default, a lambda is a small stack struct whose members are its captures and whose `operator()` is `const` and implicitly `constexpr` whenever eligible.

Every lambda expression creates its own distinct type, even when two lambdas have identical tokens: `std::is_same_v<decltype([]{}), decltype([]{})>` is always `false`.

## Value captures, reference captures, and mutable

The introducer `[...]` controls which outer variables become members inside the generated closure struct and whether those members are stored by value or by reference.

| Introducer form | Generated closure member | Mutability without `mutable` | Typical use |
| --- | --- | --- | --- |
| `[]` | None (empty class) | N/A | Stateless predicates and callbacks |
| `[x]` or `[=]` | Copy of `x` (`T x;`) | Read-only inside `operator()` | Snapshot local scalars or small values |
| `[&x]` or `[&]` | Reference (`T& x;`) | **Referent is mutable** | Mutate caller state synchronously |
| `[p = expr]` | Deduced member `auto p` (C++14) | Read-only unless `mutable` | Move-only ownership like `std::unique_ptr` |
| `[=, *this]` | Copy of enclosing object (C++17) | Copy is `const` inside `operator()` | Async tasks outliving `this` |

Notice why modifying a by-value capture requires `mutable`: the synthesized `operator()` is **`const`-qualified by default** (`[expr.prim.lambda.closure]/5`). A `const` member function cannot assign to a non-static data member `int count;`, so `[count]() { ++count; }` is rejected unless you write `mutable`, which drops `const` from `operator()`. By contrast, a `const` member function *can* mutate what a reference member points to—just like any struct containing an `int&` field—so `[&count]() { ++count; }` compiles cleanly without `mutable`.

Init-captures (`[p = std::move(ptr)]`, introduced in C++14) deduce the captured member type using `auto` rules rather than binding directly to an existing local variable name, making it trivial to move non-copyable handles such as `std::unique_ptr` into closures.

```cpp
#include <memory>
#include <utility>

void capture_demo() {
    int count = 0;

    auto by_val = [count]() mutable { return ++count; }; // Mutates its own copy
    auto by_ref = [&count]() { return ++count; };         // Mutates caller's count

    auto handle = std::make_unique<int>(42);
    auto owner = [p = std::move(handle)]() { return *p; }; // Moves ownership into closure

    (void)by_val();
    (void)by_ref();
    (void)owner();
}
```

One surprising shortcut in `[expr.prim.lambda.capture]` concerns local constants: if a local `constexpr` variable is read solely for its compile-time value (not odr-used by taking its address or binding a reference), a lambda can use it directly with an empty capture list `[]`.

## The silent dangling trap with [=] and this

Capturing by reference (`[&]` or `[&x]`) stores a raw reference inside the closure struct; returning that closure from a function or handing it to a thread pool leaves a dangling reference the moment the stack frame unwinds. Less obvious—and far more insidious—is what `[=]` does inside a member function.

> **Pitfall.** Inside a member function, `[=]` does *not* capture member variables by value. Instead, it captures the enclosing `this` pointer by value (`Widget*`), so accessing `member_` inside the lambda still reads through a pointer that dangles once the `Widget` is destroyed.

Because this trap surprised even seasoned C++ teams, C++20 deprecated implicit capture of `this` through `[=]`. In modern code, be explicit: write `[=, this]` when you consciously want the pointer, or `[=, *this]` (valid since C++17) when you want a self-contained copy of the enclosing object inside the closure.

```cpp
struct Job {
    int factor = 3;

    auto share_pointer() const {
        // Explicit pointer capture (C++20 replaces deprecated bare [=])
        return [=, this](int x) { return x * factor; };
    }

    auto snapshot_object() const {
        // Safe to outlive *this: stores a copy of the Job object (C++17+)
        return [=, *this](int x) { return x * factor; };
    }
};
```

## Stateless lambdas, function pointers, and C++20 unevaluated contexts

A captureless lambda (`[]`) carries zero state, so `[expr.prim.lambda.closure]/9` gives it a `constexpr` implicit conversion operator to a matching C-style function pointer. Prefixing `+[]` triggers that conversion via unary `+` whenever a template expects a pointer rather than an arbitrary callable. Once a lambda captures even a single byte, no conversion to a function pointer exists—a closure with state needs a separate `this`-like pointer to find its captured members, so storing it dynamically requires a type-erased wrapper such as `std::function` or `std::move_only_function` (C++23), or keeping it un-erased in a template parameter.

> **Standardese.** "The closure type for a lambda-expression has a public inline function call operator ... For a generic lambda, the function call operator is a template." — `[expr.prim.lambda.closure]`

C++20 closed two longstanding ergonomics gaps for stateless lambdas:

1. **Default-constructible and assignable.** Captureless closure types gained a defaulted default constructor and copy assignment operator, so containers like `std::set<Key, decltype([](auto a, auto b) { ... })>` work without passing a comparator object to the constructor.
2. **Valid in unevaluated contexts.** Lambdas became legal inside `decltype(...)` and `sizeof(...)`, turning custom `std::unique_ptr` deleters into clean one-liners instead of separate structs or helper functions.

```cpp
#include <memory>

void stateless_demo() {
    // Unary '+' converts a captureless lambda to a plain function pointer.
    int (*fn)(int) = +[](int x) { return x + 1; };

    // C++20: lambda directly inside an unevaluated decltype() deleter type.
    std::unique_ptr<int, decltype([](int* p) { delete p; })> ptr(new int(7));
    (void)fn(1);
    (void)ptr;
}
```

## Generic lambdas, template heads, and C++23 deducing this

Writing `auto` in a lambda parameter list (C++14) turns `operator()` into an abbreviated member function template, generating a fresh template parameter for each `auto` argument. When you need to name the deduced type—for example, to require two parameters to share the same type `T` or to call `std::forward<T>(x)` cleanly without `std::forward<decltype(x)>(x)`—C++20 lets you add an explicit template parameter list directly before the parentheses: `[]<class T>(std::vector<T>& v)`.

C++23 rounds out the closure design with two final tools:

- **`this auto self` (deducing this).** Naming the closure parameter inside the parameter list lets a lambda call itself recursively without wrapping itself in `std::function` or passing `self` as a manual second argument.
- **`static operator()`.** Decorating a captureless lambda with `static` eliminates the unused hidden `this` pointer from its calling convention (`[](int x) static { return x * 2; }`), making direct calls through the closure object as cheap as calling a free function.

```cpp
#include <vector>

void modern_lambdas() {
    // C++20 explicit template parameter list
    auto total_bytes = []<class T>(const std::vector<T>& v) {
        return v.size() * sizeof(T);
    };

    // C++23 recursive lambda via explicit object parameter
    auto fib = [](this auto self, int n) -> int {
        return n <= 1 ? n : self(n - 1) + self(n - 2);
    };

    // C++23 static operator() avoids passing an unused closure pointer
    auto double_it = [](int x) static { return x * 2; };

    std::vector<int> data{1, 2, 3};
    (void)total_bytes(data);
    (void)fib(5);
    static_assert(double_it(4) == 8);
}
```

## What to remember

- **A lambda is a struct, not magic syntax.** Captures become data members, and `operator()` is `const` (and implicitly `constexpr` when valid) unless `mutable` or `static` changes it.
- **Every lambda expression has a unique type.** Store closures with `auto`, pass them to templates, or type-erase explicitly when uniform storage is required.
- **By-value `mutable` vs. by-reference.** Reference captures can mutate their target without `mutable`, while value captures need `mutable` to mutate the closure's own copy.
- **Watch `this` inside `[=]` captures.** Prefer `[=, this]` or `[=, *this]` so object lifetimes remain obvious at the call site.
- **Use C++20/23 extensions when needed.** Template heads (`<class T>`), unevaluated `decltype([]{})`, `this auto self` recursion, and `static operator()` replace old boilerplate cleanly.

## Concept Map Outline

- **Lambdas and Closure Types:** Every lambda expression lowers to a unique unnamed closure struct holding captured members and operator().
  - **Closure Type Anatomy:** The compiler synthesizes an unnamed non-union class type for each lambda expression.
    - **Unique unnamed struct:** Two identical lambda expressions still produce two distinct closure types.
    - **const-by-default operator():** By-value captures are read-only inside operator() unless mutable removes const.
    - **Implicitly constexpr calls:** A lambda's operator() is implicitly constexpr whenever its body satisfies constant-expression rules.
  - **Capture Modes:** Capture clauses define which local variables become value or reference members in the closure.
    - **Value captures and mutable:** Value captures copy variables at lambda creation; mutable permits mutating the closure's copies.
    - **Reference captures bind aliases:** Reference captures store aliases to outer variables and can mutate them without mutable.
    - **Init-capture moves ownership:** C++14 init-captures deduce member types so move-only handles transfer into the closure.
    - **Non-odr constexpr reads:** Reading a local constexpr value without taking its address needs no capture.
  - **Object and Lifetime Traps:** Dangling reference captures and implicit this pointer captures are common lifetime hazards.
    - **Dangling reference captures:** Closures outliving local variables with reference captures cause undefined behavior when invoked.
    - **[=, this] captures pointer:** C++20 deprecated bare [=] capturing this silently; [=, this] makes pointer capture explicit.
    - **[=, *this] copies object:** C++17 [*this] stores a full copy of the enclosing object inside the closure.
  - **Stateless and Unevaluated:** Captureless lambdas behave as zero-overhead stateless callables and function-pointer sources.
    - **Converts to function pointer:** Captureless lambdas expose a constexpr conversion to a matching C function pointer.
    - **Default constructible in C++20:** Captureless closure types can be default-constructed and copy-assigned as comparator types.
    - **Allowed in decltype types:** C++20 allows lambdas in unevaluated operands such as unique_ptr custom deleters.
  - **Generic and C++23 Extensions:** Modern revisions turned lambdas into full template and recursive callable primitives.
    - **auto parameters create templates:** Each auto parameter generates an independent template type parameter on operator().
    - **Explicit template parameter list:** C++20 <class T> syntax exposes deduced types directly for constraints and forwarding.
    - **this auto self recursion:** C++23 explicit object parameters enable self-recursion, while static operator() drops unused this.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.prim.lambda.closure])

Why does `[x]() { ++x; }` fail to compile when `x` is a local `int`, and how does `mutable` fix it?

```cpp
int x = 0;
auto bad = [x]() { ++x; };
auto ok  = [x]() mutable { ++x; };
```

A. `x` is captured by `const int&` unless `mutable` switches it to `int&`.
B. Capturing `x` by value always makes `x` `const` everywhere in the enclosing function.
C. Lambdas cannot store non-static integer members without `mutable`.
D. The synthesized `operator()` is `const`-qualified by default, so `mutable` removes `const` to allow modifying the closure's copy of `x`.

**Answer (D):** The synthesized `operator()` is `const`-qualified by default, so `mutable` removes `const` to allow modifying the closure's copy of `x`.

**Why:** A lambda lowers to a closure class whose `operator()` is `const` by default (`[expr.prim.lambda.closure]/5`), preventing modification of by-value captured data members. Adding `mutable` drops the `const` qualifier from `operator()`, letting the closure mutate its own copy of `x` without changing the caller's `x`.

### Question 2 [warmup] ([expr.prim.lambda.capture], [expr.prim.lambda.closure])

Why does `auto bump = [&x]() { ++x; };` compile without `mutable`, even though `operator()` is still `const`?

```cpp
int x = 0;
auto bump = [&x]() { ++x; };
bump();
```

A. The closure stores a reference member `int&`, and a `const` member function can mutate the object a reference member refers to.
B. Reference captures automatically add `mutable` to the lambda.
C. Inside a lambda, `operator()` becomes non-`const` whenever `&` appears in the capture list.
D. `++x` resolves to a global variable lookup instead of a closure member.

**Answer (A):** The closure stores a reference member `int&`, and a `const` member function can mutate the object a reference member refers to.

**Why:** In C++, `const` on a member function applies to the closure object's direct members, not deeply through pointers or references. Because `[&x]` gives the closure an `int&` member, `const` prevents rebinding that reference (impossible anyway), while `++x` mutates the external `int` freely.

### Question 3 [tricky] ([expr.prim.lambda.capture])

Inside a member function of `Widget`, what happens if you return `[=]() { return id; }` and the `Widget` is destroyed before the returned lambda runs?

```cpp
struct Widget {
    int id = 42;
    auto make_reader() const {
        return [=]() { return id; };
    }
};
```

A. It returns `42` safely because `[=]` copies `id` by value into the closure.
B. It copies `*this` by value in C++17 and later.
C. It stores the `this` pointer by value, so invoking the returned lambda after `Widget` dies reads through a dangling pointer (UB).
D. It fails to compile in C++17 and C++23.

**Answer (C):** It stores the `this` pointer by value, so invoking the returned lambda after `Widget` dies reads through a dangling pointer (UB).

**Why:** Inside a member function, `id` is `this->id`, so `[=]` implicitly captures the `this` pointer—not a copy of `id` or `*this`. Calling the closure after `Widget` is destroyed is undefined behavior. C++20 deprecated implicit `this` capture via `[=]` in favor of explicit `[=, this]` or by-value `[=, *this]`.

### Question 4 [tricky] ([expr.prim.lambda.closure], [expr.prim.lambda.general])

What does the `static_assert` evaluate to when comparing two identical empty lambda expressions?

```cpp
constexpr bool same = std::is_same_v<decltype([]{}), decltype([]{})>;
```

A. `true`, because captureless lambdas have a canonical empty closure type.
B. `false`, because each lambda expression generates its own unique unnamed closure type.
C. `true` in C++20+, since captureless lambdas became default-constructible.
D. Ill-formed, because lambdas cannot appear inside `decltype`.

**Answer (B):** `false`, because each lambda expression generates its own unique unnamed closure type.

**Why:** Under `[expr.prim.lambda.closure]/1`, every lambda expression introduces a unique unnamed class type distinct from all others—even with identical bodies and captures. Since C++20, lambdas are also valid in unevaluated operands like `decltype([]{})`.

### Question 5 [standardese] ([expr.prim.lambda.capture], [basic.def.odr])

When `N` is a local `constexpr int N = 10;` variable inside `main`, why does `auto f = []() { return N + 1; };` compile with an empty capture list `[]`?

```cpp
int main() {
    constexpr int N = 10;
    auto f = []() { return N + 1; };
    return f();
}
```

A. Reading `N` for its integral constant value does not odr-use `N`, so `[expr.prim.lambda.capture]` requires no capture.
B. All `constexpr` local variables are silently given static storage duration.
C. `[]` automatically captures local variables that fit in a CPU register.
D. It only compiles in C++23; C++20 required `[N]` here.

**Answer (A):** Reading `N` for its integral constant value does not odr-use `N`, so `[expr.prim.lambda.capture]` requires no capture.

**Why:** A lambda may refer to a reaching local variable without capturing it if that variable is not odr-used (`[expr.prim.lambda.capture]/4`, `[basic.def.odr]`). Because `N + 1` reads `N`'s constant value immediately without taking `&N` or binding a reference to `N`, no capture is needed.

### Question 6 [standardese] ([expr.prim.lambda.general], [expr.prim.lambda.closure])

Which restriction applies to C++23 lambdas declared with a `static` function call operator (`[](int x) static { ... }`)?

```cpp
auto scale = [](int x) static { return x * 2; };
```

A. They cannot convert to a plain function pointer.
B. They cannot be `constexpr`.
C. They cannot have any captures and cannot be combined with `mutable` or an explicit object parameter.
D. They can only appear at namespace scope.

**Answer (C):** They cannot have any captures and cannot be combined with `mutable` or an explicit object parameter.

**Why:** In C++23 (`[expr.prim.lambda.general]` and `[expr.prim.lambda.closure]`), making `operator()` a `static` member function removes the implicit closure object parameter (`this`), so the closure cannot access captured members (`capture-default` or captures are ill-formed), nor can `static` be combined with `mutable` or `this auto`.

# Overload Resolution: Candidates, Viability & Ranking

> Trace the three-phase pipeline the compiler runs on every overloaded call—candidate lookup, viability filtering, and conversion-sequence ranking—to predict exact winners and ambiguities.

- **Source:** C++ Atlas (https://cppatlas.com/topics/overload-resolution)
- **Track:** Expressions and functions
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [over.match] (https://eel.is/c++draft/over.match), [over.match.viable] (https://eel.is/c++draft/over.match.viable), [over.match.best] (https://eel.is/c++draft/over.match.best), [over.ics.rank] (https://eel.is/c++draft/over.ics.rank), [over.best.ics] (https://eel.is/c++draft/over.best.ics)
- **cppreference links:** [Overload resolution](https://en.cppreference.com/w/cpp/language/overload_resolution), [Implicit conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion), [Argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl), [Converting constructor](https://en.cppreference.com/w/cpp/language/converting_constructor), [Function template](https://en.cppreference.com/w/cpp/language/function_template)
- **Prerequisites:** name-lookup-and-adl, value-categories, casts-and-qualifiers

When multiple functions share a name, the compiler does not guess by intuition or pick the first match in the file. Instead, `[over.match]` specifies a deterministic three-stage pipeline that takes the call site, narrows down the visible declarations, scores each parameter's conversion path, and declares either one unique winner or a hard ambiguity error.

> **Mental model.** Overload resolution is a tournament with strict rules: first gather all candidates (`lookup + deduction`), eliminate those that cannot accept the call (`viability`), and finally crown the unique candidate that is at least as good on *every* argument and strictly better on *at least one* (`best viable`).

## The three-phase pipeline

Every overloaded function call, constructor call, or operator expression passes through three ordered stages:

1. **Candidate functions.** Name lookup (including ADL for unqualified calls) collects all matching functions. For function templates, template argument deduction (`[temp.deduct]`) runs here: if deduction succeeds, the resulting specialization enters the candidate set; if deduction fails (SFINAE), the specialization is silently dropped before viability even begins.
2. **Viable functions.** A candidate survives Phase 2 only if its parameter count (accounting for default arguments and ellipses) matches the call, any C++20 `requires`-clause evaluates to `true` (`[over.match.viable]/3`), and an implicit conversion sequence exists for every argument.
3. **Best viable function.** All surviving candidates are compared pairwise across every argument (`[over.match.best]`). If no single candidate beats every rival, the call is ill-formed due to ambiguity.

Notice what happens *after* Phase 3 picks the winner: access control (`private`/`protected`) and `= delete` checks! Because deleted functions stay in the viable set, `void f(double) = delete;` intercepts `f(1.5)` and stops compilation rather than silently letting `void f(int)` convert `1.5` to `1`.

## The three-tier conversion hierarchy

To compare how well a viable candidate fits an argument, the compiler assigns an **Implicit Conversion Sequence (ICS)** to each parameter (`[over.best.ics]`) and ranks sequences across three top-level tiers, then three sub-ranks inside Standard Conversions.

| Tier / Sub-rank | Rank | Examples |
| --- | --- | --- |
| **Standard: Exact Match** | Highest | Identity, lvalue-to-rvalue, array-to-pointer, `int*` to `const int*` |
| **Standard: Promotion** | 2nd | `char` or `bool` to `int`, `float` to `double` (value-preserving) |
| **Standard: Conversion** | 3rd | `int` to `double`, `double` to `int`, `Derived*` to `Base*`, `const char*` to `bool` |
| **User-Defined Conversion** | 4th | Single converting constructor or `operator T()` plus standard conversions |
| **Ellipsis Conversion** | Lowest | C-style variadic `...` parameter |

That separation between Standard Conversions and User-Defined Conversions explains one of C++'s sharpest traps.

> **Pitfall.** Given `void log(bool);` and `void log(std::string);`, calling `log("hello")` invokes `log(bool)`! Converting `const char[6]` via array-to-pointer (`const char*`) and pointer-to-boolean (`bool`) is a **Standard Conversion Sequence**, which outranks the **User-Defined Conversion Sequence** calling `std::string(const char*)`.

```cpp
#include <string>

int report(bool flag) { return flag ? 1 : 0; }
int report(const std::string&) { return 2; }

void conversion_trap() {
    // Array-to-pointer + pointer-to-bool is a Standard Conversion;
    // const char* -> std::string is a User-Defined Conversion.
    int a = report("oops");          // Calls report(bool) -> 1!
    int b = report(std::string("ok")); // Calls report(const std::string&) -> 2
    (void)a;
    (void)b;
}
```

## Reference binding, const, and value-category tie-breakers

Inside the **Exact Match** tier, reference parameters follow specialized sub-rules (`[over.ics.rank]/3`) so value categories and `const`-ness dispatch cleanly without extra conversions:

- A **non-`const` lvalue** binds better to `T&` than to `const T&` (and cannot bind to `T&&`).
- A **`const` lvalue** binds only to `const T&`.
- An **rvalue** (prvalue or xvalue) binds better to `T&&` than to `const T&` (and cannot bind to non-`const` `T&`).

Be careful combining by-value overloads (`void f(T)`) with reference overloads (`void f(const T&)` or `void f(T&&)`). Passing `42` to `f(int)` vs `f(const int&)` is **ambiguous** because both parameter forms achieve Exact Match with no meaningful distinction in conversion rank (`[over.ics.rank]/3`).

## Tie-breakers: templates, specializations, and constraints

Suppose two viable candidates tie across every parameter's conversion sequence. Only then does `[over.match.best]/2` consult structural tie-breakers in strict sequence:

1. **Non-template beats template.** Between `void f(int)` and `template <class T> void f(T)`, `f(42)` selects the non-template `f(int)`.
2. **More constrained C++20 concept beats less constrained.** When two templates share identical conversion ranks, constraint **subsumption** (`[temp.constr.order]`) picks the tighter concept (for example, `std::signed_integral<T>` subsumes `std::integral<T>`).
3. **More specialized template wins.** Partial ordering (`[temp.func.order]`) prefers `template <class T> void f(T*)` over `template <class T> void f(T)` for pointers.

> **Standardese.** "Given these definitions, a viable function `F1` is defined to be a better function than another viable function `F2` if for all arguments `i`, `ICSi(F1)` is not a worse conversion sequence than `ICSi(F2)`, and then ... for some argument `j`, `ICSj(F1)` is a better conversion sequence than `ICSj(F2)`, or, if not that, ... `F1` is not a function template specialization and `F2` is a function template specialization..." — `[over.match.best]`

Read that ordering carefully! **Conversion rank ALWAYS precedes the non-template tie-breaker.** If you overload `int pick(const int&)` alongside `template <class T> int pick(T&)`, calling `pick(x)` with a mutable `int x` picks the **template** `pick<int>(int&)`—because binding `int&` to a non-`const` lvalue is a strictly better conversion sequence than binding `const int&`!

```cpp
#include <concepts>

int pick(const int&) { return 1; }
template <class T>
int pick(T&) { return 2; }

int tie(int) { return 1; }
template <class T>
int tie(T) { return 2; }

template <class T>
int check(T) requires std::integral<T> { return 1; }
template <class T>
int check(T) requires std::signed_integral<T> { return 2; }

void ranking_demo() {
    int x = 10;
    int r1 = pick(x);   // Calls template pick<int>(int&) -> 2 (better ref conversion)
    int r2 = tie(x);    // Calls non-template tie(int) -> 1 (conversion ranks tie)
    int r3 = check(x);  // Calls signed_integral overload -> 2 (subsumption)
    (void)r1;
    (void)r2;
    (void)r3;
}
```

One other specialized rule governs braced initialization (`[over.match.list]`): list-initializing a class like `std::vector<int>{5, 1}` runs a two-pass overload resolution that strongly prefers `std::initializer_list` constructors first, explaining why `std::vector<int>{5, 1}` holds two integers (`5` and `1`) while `std::vector<int>(5, 1)` holds five `1`s.

## Member functions, cv/ref-qualifiers, and C++20 operators

For non-static member functions (without C++23 explicit object parameters), the compiler treats `*this` as an extra implicit object parameter during overload resolution (`[over.match.funcs]/4`). Marking a member function `const`, `&`, or `&&` lets `*this` compete cleanly on value category and `const`-qualification—for instance, moving out of a buffer only when invoked on an rvalue (`buf.take() &&`).

Finally, C++20 streamlined comparison overloads (`[over.match.oper]`): defining a single `operator==` lets overload resolution synthesize reversed (`b == a`) and negated (`a != b`, `b != a`) candidates automatically, placing rewritten candidates just below direct non-rewritten matches in tie-breaking.

## What to remember

- **Three steps govern every call.** Gather candidates (lookup + deduction), filter viable signatures (arity + constraints + ICS), then pick the best overall conversion vector.
- **Standard Conversions always beat User-Defined Conversions.** Watch out for pointer-to-`bool` beating `const char*`-to-`std::string`.
- **Conversion rank beats non-template tie-breaking.** A template taking `T&` defeats a non-template taking `const int&` on mutable lvalues.
- **Ambiguity requires no winner, not equal winners.** Being better on parameter 1 and worse on parameter 2 makes a call ill-formed.
- **`= delete` and access checks happen last.** Deleted overloads actively catch bad conversions instead of falling back silently.

## Concept Map Outline

- **Overload Resolution:** Every overloaded call passes through candidate lookup, viability filtering, and conversion ranking.
  - **Three-Phase Pipeline:** Overload resolution constructs candidates, eliminates non-viable matches, and crowns one winner.
    - **1. Build candidate set:** Name lookup, ADL, and template argument deduction gather all visible overloads.
    - **2. Filter viable functions:** Requires matching arity, satisfied C++20 constraints, and an implicit conversion per argument.
    - **3. Pick best viable:** Selects the candidate no worse on every parameter and strictly better on at least one.
  - **Conversion Sequence Tiers:** Implicit conversion sequences rank across three strict tiers before tie-breakers apply.
    - **Standard conversion sequence:** Built-in language conversions outrank all user-defined constructors and operators.
    - **User-defined conversion sequence:** Uses at most one converting constructor or conversion operator between standard conversions.
    - **Ellipsis conversion sequence:** Matches C-style variadic parameters only when no better conversion exists.
  - **Standard Sub-Ranks:** Within standard conversions, exact matches beat promotions, which beat conversions.
    - **Exact match and qualification:** Includes identity, array-to-pointer decay, lvalue-to-rvalue, and adding const qualifiers.
    - **Promotions preserve value:** Widening char, short, or bool to int and float to double beats general conversions.
    - **Lossy and pointer conversions:** Includes int-to-double, Derived*-to-Base*, and pointer-to-bool conversions.
  - **Reference and Qualifier Rules:** Value category and const qualifiers break exact-match ties on references and *this.
    - **Lvalue prefers T& over const:** A mutable lvalue selects T& over const T& because it requires fewer cv-qualifications.
    - **Rvalue prefers T&& over const:** Temporaries and xvalues prefer rvalue references T&& over const T&.
    - **Implicit *this ref-qualifiers:** Member cv and & or && qualifiers participate as the implicit object parameter.
  - **Tie-Breakers and Traps:** When conversions tie completely, language-level rules settle templates, concepts, and deleted calls.
    - **Non-template wins equal ties:** Non-template overloads win only after parameter conversion ranks tie completely.
    - **C++20 constraint subsumption:** More constrained templates beat less constrained templates when conversions tie.
    - **Deleted and private checked last:** Overload resolution selects = delete or private winners before rejecting the call.

## Standardese Quiz Questions

### Question 1 [warmup] ([over.match.best])

Given `void f(int, double);` and `void f(double, int);`, what happens at the call site `f(1, 2);`?

```cpp
void f(int, double);
void f(double, int);

f(1, 2);
```

A. Calls `f(int, double)` because the first parameter is an exact match.
B. Ill-formed due to ambiguity because each candidate is strictly better on one argument and worse on the other.
C. Calls `f(double, int)` because the second parameter converts last.
D. Calls whichever overload was declared earlier in the translation unit.

**Answer (B):** Ill-formed due to ambiguity because each candidate is strictly better on one argument and worse on the other.

**Why:** Under `[over.match.best]`, a winner must be at least as good on *all* arguments and strictly better on at least one. On `f(1, 2)`, the first overload wins argument 1 (`int` exact vs `int->double`), while the second wins argument 2, resulting in an ambiguity error.

### Question 2 [warmup] ([over.match.viable], [dcl.fct.def.delete])

Given `void g(int);` and `void g(double) = delete;`, what happens when calling `g(2.5)`?

```cpp
void g(int);
void g(double) = delete;

g(2.5);
```

A. Calls `g(int)` by truncating `2.5` to `2` because the deleted overload is skipped during viability.
B. Ambiguous between `g(int)` and `g(double)`.
C. Compile error: `g(double)` wins overload resolution and is then rejected as deleted.
D. Undefined behavior at runtime.

**Answer (C):** Compile error: `g(double)` wins overload resolution and is then rejected as deleted.

**Why:** Deleted functions participate in Phase 1 and Phase 2 of overload resolution just like ordinary functions (`[dcl.fct.def.delete]`). Because `2.5` (`double`) is an exact match for `g(double)`, overload resolution selects `g(double)` and then diagnoses the call to a deleted function.

### Question 3 [tricky] ([over.ics.rank], [conv.bool])

Given `int log(bool);` and `int log(const std::string&);`, which overload does `log("hello")` invoke?

```cpp
#include <string>
int log(bool);
int log(const std::string&);

int r = log("hello");
```

A. `log(bool)`, because array-to-pointer plus pointer-to-boolean is a Standard Conversion Sequence.
B. `log(const std::string&)`, because `"hello"` is text.
C. Ambiguous, because both `bool` and `std::string` require one conversion step.
D. Ill-formed, because string literals cannot convert to `bool`.

**Answer (A):** `log(bool)`, because array-to-pointer plus pointer-to-boolean is a Standard Conversion Sequence.

**Why:** In `[over.ics.rank]/2`, *every* Standard Conversion Sequence strictly outranks *every* User-Defined Conversion Sequence. Turning `const char[6]` into `bool` (array-to-pointer + boolean conversion) is purely a Standard Conversion, defeating `std::string(const char*)`.

### Question 4 [tricky] ([over.match.best], [over.ics.rank])

Given `int pick(const int&);` and `template <class T> int pick(T&);`, what does `int x = 10; pick(x);` return?

```cpp
int pick(const int&) { return 1; }
template <class T> int pick(T&) { return 2; }

int x = 10;
int r = pick(x);
```

A. `1`, because non-template functions always beat function templates.
B. Compile error: ambiguous between `const int&` and `T&`.
C. `1`, because `const int&` is preferred for scalar types.
D. `2`, because `int&` has a strictly better reference-binding conversion than `const int&`, before template tie-breaking runs.

**Answer (D):** `2`, because `int&` has a strictly better reference-binding conversion than `const int&`, before template tie-breaking runs.

**Why:** Overload resolution compares conversion sequences *before* applying the non-template-vs-template tie-breaker (`[over.match.best]/2`). Binding mutable lvalue `x` to `int&` (deduced from `T&`) is strictly better than binding to `const int&` (`[over.ics.rank]/3.2.6`), so the template wins.

### Question 5 [standardese] ([over.best.ics], [over.ics.rank])

Why does declaring both `void h(int);` and `void h(const int&);` make the call `h(5)` ambiguous?

```cpp
void h(int);
void h(const int&);

h(5);
```

A. `const int&` cannot bind to a prvalue literal `5`.
B. Both `int` (identity/Exact Match) and `const int&` (Exact Match binding a materialized temporary) have indistinguishable conversion ranks.
C. By-value `int` always ranks lower than reference parameters.
D. Only `h(const int&)` is viable for literals.

**Answer (B):** Both `int` (identity/Exact Match) and `const int&` (Exact Match binding a materialized temporary) have indistinguishable conversion ranks.

**Why:** Under `[over.best.ics]` and `[over.ics.rank]`, passing a prvalue `5` to `int` is an Identity Exact Match, and binding it to `const int&` is also an Exact Match with no distinguishing sub-rank difference against a non-reference parameter. Neither sequence is better, so the call is ambiguous.

### Question 6 [standardese] ([over.match.oper])

In C++20 and C++23, why does `7 != Key{7}` compile when `Key` only defines `friend bool operator==(const Key&, int);`?

```cpp
struct Key {
    int id;
    friend bool operator==(const Key& a, int b) { return a.id == b; }
};
bool diff = (7 != Key{7});
```

A. The compiler generates an implicit conversion from `int` to `Key` automatically.
B. Friend declarations inject free operators for both argument orders automatically.
C. `[over.match.oper]` synthesizes rewritten `!=` and reversed `operator==` candidates during overload resolution.
D. Because `Key` is an aggregate, `!=` performs memberwise comparison.

**Answer (C):** `[over.match.oper]` synthesizes rewritten `!=` and reversed `operator==` candidates during overload resolution.

**Why:** In C++20 (`[over.match.oper]/3`), an expression `a != b` considers rewritten candidates `!(a == b)` and `!(b == a)` synthesized from viable `operator==` overloads, allowing `7 != Key{7}` to resolve to `!(Key{7} == 7)` without writing boilerplate reverse overloads.

# Operator overloading

> An overloaded operator is an ordinary function with a special name that an operator expression calls. Arity, precedence and associativity never change, but evaluation guarantees can, and a few operators must be members.

- **Source:** C++ Atlas (https://cppatlas.com/topics/operator-overloading)
- **Track:** Expressions and functions
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [over.oper] (https://eel.is/c++draft/over.oper), [over.match.oper] (https://eel.is/c++draft/over.match.oper), [over.call] (https://eel.is/c++draft/over.call), [over.sub] (https://eel.is/c++draft/over.sub), [over.ref] (https://eel.is/c++draft/over.ref), [over.inc] (https://eel.is/c++draft/over.inc), [over.literal] (https://eel.is/c++draft/over.literal), [lex.ext] (https://eel.is/c++draft/lex.ext), [expr.log.and] (https://eel.is/c++draft/expr.log.and), [expr.comma] (https://eel.is/c++draft/expr.comma)
- **cppreference links:** [Operator overloading](https://en.cppreference.com/w/cpp/language/operators), [User-defined literals](https://en.cppreference.com/w/cpp/language/user_literal), [Member access operators](https://en.cppreference.com/w/cpp/language/operator_member_access), [Increment/decrement operators](https://en.cppreference.com/w/cpp/language/operator_incdec), [Logical operators](https://en.cppreference.com/w/cpp/language/operator_logical)
- **Prerequisites:** overload-resolution, name-lookup-and-adl, value-categories

## The one idea

An overloaded operator is a function. When at least one operand of an operator expression has class or enumeration type, the compiler gathers candidate functions named `operator@`, adds the built-in candidates, and runs ordinary overload resolution. Whatever wins is called like any other function, with the operands as arguments.

Everything that surprises people follows from that. The grammar does not change, so precedence, associativity and the number of operands are fixed by the token you chose, not by your function. But the *evaluation* rules of the built-in operator do not come along: a function call evaluates all of its arguments before the body runs, which is why an overloaded `&&` cannot short-circuit.

> **Mental model.** `a + b` is spelled like arithmetic and parsed like arithmetic, then dispatched like `operator+(a, b)` or `a.operator+(b)`. The parse belongs to the language; the meaning belongs to your function.

Candidate gathering and ranking are the subject of overload-resolution; comparison operators, including the rewriting that C++20 introduced, are covered in three-way-comparison. This topic is about which operator functions you may declare, where they must live, and how each special form behaves.

## What can be overloaded, and what must be a member

Almost every operator can be overloaded, including `->*`, the comma, `co_await`, `new` and `delete`, and conversion functions. A handful cannot: scope resolution `::`, member access `.`, pointer-to-member access `.*`, the conditional operator `?:`, and the keyword operators `sizeof`, `alignof`, `typeid` and `noexcept`. You cannot invent new operator tokens, and you cannot change how many operands an operator takes.

A non-member operator function needs at least one parameter whose type is a class, an enumeration, or a reference to one. That rule protects the built-in meaning of `1 + 2`.

```cpp
// int operator+(int, int);   // ill-formed: no class or enumeration parameter
enum class Flags { a = 1, b = 2 };
constexpr Flags operator|(Flags x, Flags y) {   // OK: enumeration operands
  return Flags(int(x) | int(y));
}
```

Four operators must be member functions: assignment `=`, function call `()`, subscript `[]`, and class member access `->`. The usual explanation for assignment is that every class already has an implicitly declared copy assignment operator, and a free function competing with it would be inconsistent. The other three are tied to the object they are applied to. C++23 relaxed one detail: `operator()` and `operator[]` may now be *static* member functions, which removes the hidden `this` parameter for stateless function objects.

> **Standardese.** [over.oper] says an operator function shall be a member function or have at least one parameter of class or enumeration type, and that operator functions cannot have default arguments except where the specific subclause allows it. [over.call] and, since C++23, [over.sub] are the two subclauses that allow them.

## Member or non-member: the symmetry argument

A member operator treats its left operand as the implicit object argument, and the implicit object argument never undergoes user-defined conversions. So a member `operator+` accepts conversions on the right but not on the left, and `2 + v` fails where `v + 2` works.

```cpp
struct Money {
  long cents;
  Money(long c) : cents(c) {}                  // implicit conversion from long
  Money operator+(const Money& o) const { return cents + o.cents; }
};

void demo(Money m) {
  Money a = m + 5;     // OK: 5 converts to Money for the parameter
  // Money b = 5 + m;  // ill-formed: 5 is not converted to the object argument
  (void)a;
}
```

The usual fix is a non-member, and the idiomatic non-member is a *hidden friend*: a `friend` function defined inside the class. It has the access a member would have, both operands get the same conversions, and because it is only found by argument-dependent lookup, it does not pollute overload sets for unrelated types.

```cpp
class Money {
  long cents_;
public:
  Money(long c) : cents_(c) {}
  friend Money operator+(Money a, Money b) { return a.cents_ + b.cents_; }
};

Money total(Money m) { return 5 + m; }   // OK: symmetric
```

The rule of thumb: operators that modify their left operand (`+=`, `<<=`, `=`, prefix `++`) are members; symmetric binary operators (`+`, `==`, `<=>`) are hidden friends or non-members; stream insertion `operator<<` cannot be a member of your class because the left operand is the stream.

## Calls, subscripts and arrows

`operator()` is the one operator with arbitrary arity and default arguments, which is what makes function objects and lambdas possible. Since C++23 it can be `static`, and the lambdas topic shows the matching `static` lambda syntax.

Since C++23, `operator[]` also takes any number of parameters, including zero, and may have default arguments. That is multidimensional subscripting, the access syntax `std::mdspan` uses.

```cpp
#include <cstddef>

struct Grid {
  int cells[4][4]{};
  int& operator[](std::size_t r, std::size_t c) { return cells[r][c]; }  // C++23
  static int operator()(int a, int b) { return a * b; }                // C++23
};

int demo() {
  Grid g;
  g[1, 2] = 5;              // calls operator[](1, 2)
  return g[1, 2] + Grid{}(2, 3);
}
```

To make room for that syntax, a comma expression directly inside square brackets was deprecated in C++20, and in C++23 the built-in subscript requires exactly one expression, so `arr[1, 2]` on a plain array is ill-formed. Clang rejects it; GCC still accepts it with a warning and treats it as the old comma expression, which is an extension.

`operator->` is unique because it is applied again to whatever it returns. The expression `x->m` becomes `(x.operator->())->m`, and if that result is itself a class object, its `operator->` is called, and so on until a raw pointer appears. This drill-down is what lets a smart pointer or a locking proxy return another proxy.

```cpp
#include <cstdio>

struct Raw   { int x = 42; };
struct Inner { Raw r;   Raw*   operator->() { std::puts("Inner"); return &r; } };
struct Outer { Inner i; Inner& operator->() { std::puts("Outer"); return i; } };

int read() { Outer o; return o->x; }   // prints Outer, then Inner; returns 42
```

`operator->*` gets no such treatment; it is an ordinary binary operator.

## Increment, decrement, and the dummy int

Prefix and postfix forms share a token, so the language tells them apart with a dummy parameter. `operator++()` is prefix; `operator++(int)` is postfix. When you write `x++`, the postfix function is called with the argument `0`. An explicit call `x.operator++(5)` passes 5, which nobody should rely on.

```cpp
struct Counter {
  int n = 0;
  Counter& operator++() { ++n; return *this; }               // prefix: return self
  Counter  operator++(int) { Counter old = *this; ++*this; return old; }  // postfix: copy
};
```

The conventional signatures follow the built-in operators: prefix returns an lvalue reference, postfix returns the old value by value. That copy is why prefix increment is the habit for iterators. Nothing in the language enforces these return types; they are convention.

## Operators that lose their built-in guarantees

Built-in `&&` and `||` evaluate the left operand first and skip the right one when the result is already known. Built-in comma evaluates left, discards it, then evaluates right. An overloaded version is a function call, so both operands are always evaluated.

```cpp
#include <cstdio>

struct B { bool v; };
B lhs() { std::puts("lhs"); return {false}; }
B rhs() { std::puts("rhs"); return {true}; }
bool operator&&(B a, B b) { return a.v && b.v; }

bool test() { return lhs() && rhs(); }   // prints lhs, then rhs: no short-circuit
```

C++17 recovered one piece. [over.match.oper] says that when an operator expression calls an overloaded operator, the operands are sequenced in the order prescribed for the built-in operator. So the left operand of an overloaded `&&`, `||` or comma is sequenced before the right one. The same rule makes overloaded `<<`, `>>` and subscript evaluate left to right, and overloaded assignment evaluate its right operand first. Before C++17 the order was unspecified. Short-circuiting is still gone, and it cannot be brought back.

> **Pitfall.** Overloading `&&`, `||` or the comma operator for a type that will appear in conditions silently changes code that looks like a guard, such as `p && p->ok()`. Expression-template libraries do it deliberately; ordinary types should not.

Unary `&` can also be overloaded, which is why generic code takes addresses with `std::addressof` rather than `&x`.

`operator new` and `operator delete` are overloadable too, but they are allocation functions, not operators applied to operands: a `new` expression calls them to obtain storage and then constructs the object itself. Their replacement and class-specific forms belong to dynamic-allocation-new-and-delete.

## User-defined literals

A literal operator gives a suffix meaning: `operator""_km` lets you write `12.5_km`. Suffixes that do not begin with an underscore are reserved for the standard library, as in `"abc"s` and `10ms`. C++23 deprecated the old spelling with a space between the quotes and the suffix, `operator"" _km`; in that form the suffix is a separate identifier, so a suffix such as `_Km` collides with the reserved-identifier rules.

The compiler chooses the operator from the kind of literal, and the permitted parameter lists are fixed:

- integer literal: `(unsigned long long)`, else the raw form `(const char*)`, else a numeric literal operator template `template <char...>`;
- floating literal: `(long double)`, else the raw form, else the template;
- string literal: `(const char*, std::size_t)`, or since C++20 a template whose parameter is a class-type non-type template parameter;
- character literal: `(char)` or the corresponding `char8_t`, `char16_t`, `char32_t` or `wchar_t` overload.

There is no conversion between these: if you only declare the `long double` form, `12_km` is ill-formed, because an integer literal never looks for it.

```cpp
constexpr long double operator""_km(long double v) { return v * 1000; }
constexpr long double operator""_km(unsigned long long v) { return v * 1000.0L; }

static_assert(12_km == 12000);    // needs the unsigned long long overload
static_assert(1.5_km == 1500);    // uses the long double overload
```

Literal operators are found by ordinary unqualified lookup, which is why the standard library puts its own in inline namespaces such as `std::literals::chrono_literals` that you bring in with a `using` directive.

## What to remember

- An overloaded operator is a function chosen by overload resolution; precedence, associativity and arity never change.
- `::`, `.`, `.*`, `?:`, `sizeof`, `alignof`, `typeid` and `noexcept` cannot be overloaded; `->*`, comma and `co_await` can.
- A non-member operator needs a class or enumeration parameter; `=`, `()`, `[]` and `->` must be members.
- C++23 allows `static operator()` and `static operator[]`, and multi-parameter `operator[]` with default arguments.
- Member operators do not convert their left operand; hidden friends give symmetric conversions and ADL-only visibility.
- `operator->` is reapplied to its result until a raw pointer appears; `operator->*` is not.
- Postfix `++` is `operator++(int)` and receives `0`.
- Overloaded `&&`, `||` and comma always evaluate both operands; since C++17 the left one is sequenced first.
- A literal operator only matches its own literal kind; `12_km` needs an integer or raw form.

## Concept Map Outline

- **Operator overloading:** An operator expression on class or enum operands calls a function chosen by overload resolution.
  - **What can be overloaded:** Nearly every operator, but never its precedence, associativity or arity.
    - **Not overloadable:** ::, ., .*, ?:, sizeof, alignof, typeid and noexcept.
    - **Overloadable surprises:** ->*, the comma, co_await, new, delete and conversion functions can all be overloaded.
    - **Class or enum operand:** A non-member operator needs a parameter of class or enumeration type, so int + int stays built-in.
  - **Member or non-member:** Some operators must be members; symmetric ones are better as non-members.
    - **Must be members:** =, (), [] and -> can only be member functions.
    - **Left operand:** A member never converts its left operand, so 2 + v fails when only v + 2 is a member.
    - **Hidden friends:** Friends defined in the class get symmetric conversions and are found only by ADL.
  - **Call, subscript, arrow:** The three object-bound forms with special rules.
    - **operator():** Any arity and default arguments; may be static since C++23.
    - **Multidimensional []:** Since C++23 operator[] takes any number of parameters, may be static, and may have defaults.
    - **Comma in brackets:** Built-in a[1, 2] is ill-formed in C++23; GCC still accepts it with a warning.
    - **-> drill-down:** x->m applies operator-> repeatedly until a raw pointer results.
  - **Increment and decrement:** Prefix and postfix share a token and differ by a dummy parameter.
    - **Dummy int:** operator++(int) is postfix; x++ calls it with the argument 0.
    - **Return conventions:** Prefix returns *this by reference, postfix returns the old value by copy.
  - **Lost guarantees:** Overloads are function calls, so built-in evaluation rules do not all survive.
    - **No short-circuit:** Overloaded &&, || and comma always evaluate both operands.
    - **C++17 sequencing:** Operands of an overloaded operator follow the built-in operator's sequencing order.
    - **Unary &:** Can be overloaded, so generic code uses std::addressof.
    - **new and delete:** Allocation functions that supply storage; the new expression still constructs the object.
  - **User-defined literals:** operator""_suffix gives a literal suffix a meaning.
    - **Underscore suffixes:** Suffixes without a leading underscore are reserved for the standard library.
    - **Fixed parameter lists:** Integer literals want unsigned long long, floating ones long double, else raw const char* or a template.
    - **No conversions:** With only a long double operator, 12_km is ill-formed.
    - **Spaced form deprecated:** C++23 deprecates operator"" _x with a space before the suffix.

## Standardese Quiz Questions

### Question 1 [warmup] ([over.oper], [over.ass])

Which of these operators can only be overloaded as a member function?

A. `operator+`
B. `operator<<`
C. `operator=`
D. `operator==`
E. `operator!`

**Answer (C):** `operator=`

**Why:** Assignment, function call, subscript and `->` must be member functions; every class already has an implicitly declared copy assignment operator, and a free `operator=` is rejected outright. The others may be members or non-members. `operator<<` is tempting because it is usually a non-member, but that is a convention forced by the stream being the left operand, not a rule in either direction.

### Question 2 [warmup] ([over.match.oper], [over.match.funcs])

Is this program well-formed?

```cpp
struct V {
  int x;
  V operator+(int n) const { return {x + n}; }
};

int main() {
  V v{1};
  V w = 2 + v;
  (void)w;
}
```

A. Well-formed: addition is commutative, so the compiler swaps the operands
B. Ill-formed: no `operator+` accepts an `int` on the left and a `V` on the right
C. Well-formed: `2` is converted to `V` and the member is called on it
D. Well-formed only since C++20, which adds reversed candidates for `+`

**Answer (B):** Ill-formed: no `operator+` accepts an `int` on the left and a `V` on the right

**Why:** A member `operator+` makes the left operand the implicit object argument, so it only matches `V + int`. The compiler never swaps the operands of `+`; C++20 reversed candidates exist only for `==` and the relational operators via `<=>`. Converting `2` to `V` is not possible here, and user-defined conversions are never applied to the implicit object argument anyway.

### Question 3 [warmup] ([over.inc])

What does this program print?

```cpp
#include <cstdio>

struct C {
  int n = 0;
  C& operator++() { ++n; return *this; }
  C operator++(int k) {
    std::printf("k=%d\n", k);
    C old = *this;
    ++n;
    return old;
  }
};

int main() {
  C c;
  c++;
  c.operator++(5);
  std::printf("%d\n", c.n);
}
```

A. `k=1`, `k=5`, `2`
B. `k=0`, `2` only; an explicit call to the postfix form is ill-formed
C. `k=5`, `1`; `c++` calls the prefix overload
D. `k=0`, `k=5`, `2`

**Answer (D):** `k=0`, `k=5`, `2`

**Why:** The `int` parameter only distinguishes postfix from prefix. When the postfix form is invoked through `c++`, the standard says it is called with the argument zero. Calling `operator++` by name is an ordinary member function call, so you may pass any `int`, here 5. Each call increments `n` once, so the final value is 2.

### Question 4 [tricky] ([over.match.oper], [expr.log.and], [expr.call])

In C++23, what does this program print?

```cpp
#include <cstdio>

struct B { bool v; };
B f() { std::puts("f"); return {false}; }
B g() { std::puts("g"); return {true}; }
bool operator&&(B a, B b) { std::puts("&&"); return a.v && b.v; }

int main() {
  bool r = f() && g();
  std::printf("%d\n", r);
}
```

A. `f`, `g`, `&&`, `0`
B. `f`, `0`: `g()` is skipped because the left operand is false
C. `f`, `g`, `&&`, `0`, but `f` and `g` may appear in either order
D. `g`, `f`, `&&`, `0`: function arguments are evaluated right to left

**Answer (A):** `f`, `g`, `&&`, `0`

**Why:** An overloaded `&&` is a function call, and both arguments are evaluated before the body runs, so there is no short-circuit. Since C++17, [over.match.oper] sequences the operands of an overloaded operator in the order prescribed for the built-in one, so `f()` is evaluated before `g()`. The third option describes the pre-C++17 rule, when the order was unspecified.

### Question 5 [tricky] ([over.ref], [over.match.oper])

What does this program print?

```cpp
#include <cstdio>

struct Raw { int x = 42; };
struct Inner {
  Raw r;
  Raw* operator->() { std::puts("Inner->"); return &r; }
};
struct Outer {
  Inner i;
  Inner& operator->() { std::puts("Outer->"); return i; }
};

int main() {
  Outer o;
  std::printf("%d\n", o->x);
}
```

A. Nothing: ill-formed, because `operator->` must return a pointer
B. `Outer->`, then `42`
C. `Outer->`, `Inner->`, then `42`
D. Nothing: ill-formed, because `Inner` has no member `x`

**Answer (C):** `Outer->`, `Inner->`, then `42`

**Why:** `o->x` is interpreted as `(o.operator->())->x`. The result is an `Inner` lvalue, which is a class type, so `->` is applied to it again, calling `Inner::operator->`, which yields a `Raw*`, and the built-in `->` finishes the job. `operator->` may return any class type that itself supports `->`; only the final step must produce a pointer.

### Question 6 [tricky] ([lex.ext], [over.literal])

Is this program well-formed?

```cpp
long double operator""_km(long double x) { return x * 1000; }

int main() {
  auto d = 12_km;
  (void)d;
}
```

A. Well-formed: `12` is converted to `long double` and `d` is 12000
B. Ill-formed: an integer literal never selects the `long double` literal operator
C. Well-formed, but `d` has type `unsigned long long`
D. Ill-formed: literal operators must be declared `constexpr`

**Answer (B):** Ill-formed: an integer literal never selects the `long double` literal operator

**Why:** The literal operator is chosen from the kind of literal, with no conversions. For the integer literal `12_km`, lookup tries `operator""_km(unsigned long long)`, then the raw form taking `const char*`, then a numeric literal operator template; none exists, so the program is ill-formed. Writing `12.0_km` or adding an `unsigned long long` overload fixes it. `constexpr` is optional.

### Question 7 [standardese] ([over.oper])

Which of these operators cannot be overloaded?

A. `->*`
B. `,` (comma)
C. `co_await`
D. `.*`
E. `&&`

**Answer (D):** `.*`

**Why:** The pointer-to-member operator `.*` is on the short list of operators that cannot be overloaded, with `::`, `.` and `?:`. Its sibling `->*` can be overloaded, as an ordinary binary operator with no drill-down. The comma, `co_await` and `&&` are all overloadable, although overloading the comma or `&&` loses the built-in short-circuit behaviour.

### Question 8 [standardese] ([over.call], [over.sub], [over.oper])

In C++23, what does `main` return?

```cpp
struct Grid {
  static int operator()(int a, int b) { return a * b; }
  int operator[](int i = 7) const { return i; }
};

int main() {
  return Grid{}(3, 4) + Grid{}[];
}
```

A. 19
B. Ill-formed: `operator()` cannot be a static member function
C. Ill-formed: `operator[]` cannot have a default argument
D. Ill-formed: a subscript expression needs at least one operand

**Answer (A):** 19

**Why:** C++23 (P1169 and P2589) allows `operator()` and `operator[]` to be static member functions, and P2128 lets `operator[]` take any number of parameters, including zero, with default arguments. So `Grid{}(3, 4)` is 12 and `Grid{}[]` uses the default 7, giving 19. Each of the other options was true in C++20.

# Three-way comparison

> C++20 lets one operator<=> answer less, equal or greater, and lets the compiler rewrite the other relational operators in terms of it. Equality stays separate, and the rewriting rules for == changed the meaning of some existing code.

- **Source:** C++ Atlas (https://cppatlas.com/topics/three-way-comparison)
- **Track:** Expressions and functions
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [expr.spaceship] (https://eel.is/c++draft/expr.spaceship), [cmp.categories] (https://eel.is/c++draft/cmp.categories), [class.compare.default] (https://eel.is/c++draft/class.compare.default), [class.eq] (https://eel.is/c++draft/class.eq), [class.spaceship] (https://eel.is/c++draft/class.spaceship), [over.match.oper] (https://eel.is/c++draft/over.match.oper), [over.match.best] (https://eel.is/c++draft/over.match.best), [comparisons.three.way] (https://eel.is/c++draft/comparisons.three.way)
- **cppreference links:** [Default comparisons](https://en.cppreference.com/w/cpp/language/default_comparisons), [Comparison operators](https://en.cppreference.com/w/cpp/language/operator_comparison), [std::strong_ordering](https://en.cppreference.com/w/cpp/utility/compare/strong_ordering), [std::partial_ordering](https://en.cppreference.com/w/cpp/utility/compare/partial_ordering), [std::compare_three_way](https://en.cppreference.com/w/cpp/utility/compare/compare_three_way)
- **Prerequisites:** operator-overloading, overload-resolution

## The one idea

Before C++20, a fully comparable type needed six operators, and they could disagree with each other. C++20 splits the job in two. **Ordering** is answered by one function, `operator<=>`, which returns a value saying less, equivalent, greater, or, for some types, unordered. **Equality** is answered by `operator==`. The compiler then rewrites `<`, `<=`, `>` and `>=` in terms of `<=>`, and `!=` in terms of `==`, and it is also allowed to swap the operands.

The two halves are deliberately independent. Writing `<=>` by hand does not give you `==`, because equality can often be answered far more cheaply than ordering: two strings of different lengths are unequal without looking at a single character.

> **Mental model.** You write at most two functions, `==` and `<=>`. The compiler derives the other four operators, and it tries each comparison with the operands in both orders.

## Comparison categories

The result of `<=>` is one of three class types from `<compare>`, and the type itself documents what kind of order you have.

| Category | Values | Meaning of "equivalent" |
|---|---|---|
| `std::strong_ordering` | `less`, `equal`, `greater` | interchangeable values |
| `std::weak_ordering` | `less`, `equivalent`, `greater` | same rank, possibly distinguishable |
| `std::partial_ordering` | `less`, `equivalent`, `greater`, `unordered` | some pairs cannot be compared |

A case-insensitive string comparison is a weak ordering: `"Abc"` and `"abc"` are equivalent but not identical. Floating-point numbers are partially ordered, because a NaN is neither less than, equal to, nor greater than anything, including itself.

Conversions only go towards weaker guarantees. A `strong_ordering` converts implicitly to `weak_ordering` and to `partial_ordering`, and a `weak_ordering` converts to `partial_ordering`. Nothing converts the other way, because that would invent a guarantee.

You use a result by comparing it with the literal `0`: `r < 0` means less, `r == 0` means equal or equivalent. The standard says comparing a category value with anything other than a literal zero is undefined behaviour; library implementations make the parameter a type that only a literal `0` converts to, so `r == 1` is rejected in practice. The named functions `std::is_lt`, `std::is_eq` and friends say the same thing in words.

```cpp
#include <compare>
#include <cmath>

void demo() {
  double nan = std::nan("");
  auto r = nan <=> 1.0;            // std::partial_ordering::unordered
  bool all_false = !(r < 0) && !(r == 0) && !(r > 0);   // true
  (void)all_false;
}
```

## The built-in `<=>`

For integers, enumerations and pointers, the built-in `<=>` yields `std::strong_ordering`. For floating-point operands it yields `std::partial_ordering`. Arithmetic operands go through the usual arithmetic conversions first, but with a twist that makes `<=>` stricter than `<`: if the conversion would be narrowing, other than integer to floating point, the program is ill-formed.

```cpp
#include <compare>

bool old_way = -1 < 1u;              // compiles: -1 becomes a huge unsigned, so false
// auto new_way = -1 <=> 1u;         // ill-formed: int to unsigned is narrowing
```

When the narrowing operand is a variable rather than a constant, Clang rejects it but GCC only warns by default and needs `-pedantic-errors` to reject it, so do not use GCC's acceptance as evidence. For pointers, the built-in comparison has an unspecified result for pointers into unrelated objects, just as `<` does.

## Defaulted `<=>` and `==`

`= default` asks the compiler to compare memberwise. A defaulted `operator==` compares base subobjects in declaration order, then non-static data members in declaration order, and stops at the first inequality. A defaulted `operator<=>` does the same with `<=>`, returning the first result that is not equal.

If you declare `auto operator<=>(const T&) const = default;` and do not declare any `operator==`, the compiler also declares a defaulted `operator==` for you. That is the only way `==` comes from `<=>`, and it is still memberwise `==`, not a call to `<=>`.

```cpp
#include <compare>

struct Version {
  int major, minor, patch;
  auto operator<=>(const Version&) const = default;   // also declares == = default
};

static_assert(Version{1, 2, 3} < Version{1, 3, 0});
static_assert(Version{1, 2, 3} == Version{1, 2, 3});
```

With an `auto` return type, the result is the common comparison category of all the member comparisons: one `double` member makes the whole thing `std::partial_ordering`. If some member has no usable `<=>`, the defaulted `operator<=>` with `auto` is defined as deleted.

If you name the return type instead, the compiler is allowed to fall back on `==` and `<` for members that lack `<=>`. [class.spaceship] calls this the synthesized three-way comparison: it uses `<=>` when available and otherwise builds the requested category from `a == b` and `a < b`. That is how a C++20 type can wrap a pre-C++20 type that only has `<` and `==`.

```cpp
#include <compare>

struct Legacy {
  int v;
  bool operator<(const Legacy& o) const { return v < o.v; }
  bool operator==(const Legacy& o) const { return v == o.v; }
};

struct Bad  { Legacy l; auto operator<=>(const Bad&) const = default; };   // deleted
struct Good { Legacy l; std::weak_ordering operator<=>(const Good&) const = default; };
```

A defaulted comparison is also deleted when the class has a reference member or is a union-like class, since there is no obvious meaning to compare.

> **Pitfall.** A hand-written `operator<=>` gives you `<`, `<=`, `>` and `>=` but not `==` or `!=`. Add `bool operator==(const T&) const = default;` or write `==` yourself.

## Rewritten and reversed candidates

For a relational expression `a < b`, overload resolution considers, in addition to every `operator<`, the rewritten candidates `(a <=> b) < 0` and, reversed, `0 < (b <=> a)`. For `a != b` it considers `!(a == b)` and `!(b == a)`. For `a == b` it adds the reversed `b == a`. This is why one member `operator==(int) const` makes both `s == 42` and `42 == s` work.

```cpp
#include <compare>

struct Id {
  int v;
  constexpr bool operator==(int x) const { return v == x; }
  constexpr std::strong_ordering operator<=>(int x) const { return v <=> x; }
};

static_assert(42 == Id{42});    // reversed: Id{42} == 42
static_assert(42 >  Id{7});     // rewritten: 0 > (Id{7} <=> 42)
static_assert(Id{1} != 2);      // rewritten: !(Id{1} == 2)
```

When a rewritten or reversed candidate ties with an ordinary one on conversions, [over.match.best] prefers the ordinary candidate, and prefers a non-reversed rewrite over a reversed one. A rewritten `!=` or reversed `==` must return `bool`; if the selected `operator==` returns something else, the program is ill-formed.

> **Standardese.** [over.match.oper] defines the rewritten candidates. For `x < y` and the other relational operators they are the `operator<=>` functions, tried as `x <=> y` and reversed as `y <=> x`. For `x != y` they are the `operator==` functions, tried both ways round. For `x == y` they are the reversed `y == x`, and for `x <=> y` the reversed `y <=> x`, used as `0 <=> (y <=> x)`.

## What C++20 broke

Reversed candidates are added silently to code written before C++20, and some of that code changed meaning. The classic case is a member `operator==` that forgot `const`:

```cpp
struct S {
  int v;
  bool operator==(const S& o) { return v == o.v; }   // not const
};

bool same(S a, S b) { return a == b; }
```

For `a == b`, the ordinary candidate binds `a` to the non-const object parameter exactly and `b` to `const S&`. The reversed candidate does the opposite. Each is better for one argument, so by the C++20 rules the call is ambiguous. GCC and Clang accept it with a warning and pick the ordinary candidate; the fix is to make the operator `const`.

P2468, adopted for C++23 and applied by compilers as a defect report against C++20, added an escape hatch for code like this: if a matching `operator!=` is declared in the same scope as an `operator==`, that `operator==` is not used for reversed or rewritten candidates. A pre-C++20 class that defines both operators keeps its old behaviour.

## Library support

`std::compare_three_way` is a function object whose call operator computes `a <=> b`, constrained on the `std::three_way_comparable_with` concept. For pointers it gives an implementation-defined strict total order even where the built-in `<=>` is unspecified, which is what you want as a container key.

The library also has an exposition-only helper, *synth-three-way*, used to define `<=>` for `std::pair`, `std::tuple`, `std::array` and the other containers. It calls `<=>` when the element type has one and otherwise falls back to `<`, producing `std::weak_ordering`. So a `std::pair<Legacy, int>` supports `<=>` even though `Legacy` does not. This is related to, but not the same as, the core language's synthesized three-way comparison, which only applies when a defaulted `<=>` names its return type.

For floating point, `std::strong_order` provides the IEEE total order in which every NaN has a place, and `std::weak_order` and `std::partial_order` give the corresponding weaker orders. What a comparator must satisfy to be used by sorting algorithms is the subject of strict-weak-ordering-and-comparators.

## What to remember

- `<=>` answers ordering, `==` answers equality; the compiler rewrites `<`, `<=`, `>`, `>=` from the first and `!=` from the second.
- `strong_ordering` converts to `weak_ordering` converts to `partial_ordering`, never backwards.
- Compare a category value only with literal `0`, or use `std::is_lt` and friends.
- Built-in `<=>` on floating point is `partial_ordering`; NaN gives `unordered`, and every relational test is false.
- `-1 <=> 1u` is ill-formed because the conversion narrows, even though `-1 < 1u` compiles.
- A hand-written `<=>` does not provide `==`; only a defaulted `<=>` implicitly declares a defaulted `==`.
- Defaulted `<=>` with `auto` is deleted if a member lacks `<=>`; naming the return type lets it fall back on `==` and `<`.
- Reversed candidates make `42 == s` work, and can make non-const member `operator==` ambiguous.
- A matching `operator!=` suppresses rewriting for that `operator==` (P2468).

## Concept Map Outline

- **Three-way comparison:** operator<=> answers ordering, operator== answers equality, and the compiler rewrites the rest.
  - **Comparison categories:** The result type of <=> says what kind of order the type has.
    - **strong_ordering:** Equal values are interchangeable; built-in for integers, enums and pointers.
    - **weak_ordering:** Equivalent values may still be distinguishable, as in case-insensitive strings.
    - **partial_ordering:** Adds unordered; built-in <=> on floating point returns it, and NaN is unordered.
    - **One-way conversions:** strong converts to weak converts to partial, never the other way.
    - **Compare with literal 0:** Test results as r < 0 or r == 0; comparing with any other value is undefined.
  - **Built-in <=>:** Applies the usual arithmetic conversions, but more strictly than <.
    - **No narrowing:** -1 <=> 1u is ill-formed because int to unsigned narrows.
    - **Unrelated pointers:** Comparing pointers into unrelated objects gives an unspecified result.
  - **Defaulting:** = default compares bases, then members, in declaration order.
    - **Implicit ==:** A defaulted <=> declares a defaulted == only if no operator== is declared.
    - **auto return type:** Deduces the common category; deleted if any member lacks <=>.
    - **Named return type:** Lets the compiler synthesize the result from == and < for legacy members.
    - **Deleted cases:** Reference members and union-like classes make defaulted comparisons deleted.
  - **Rewritten candidates:** Overload resolution adds rewritten and reversed forms for comparisons.
    - **Relational:** a < b also tries (a <=> b) < 0 and 0 < (b <=> a).
    - **Equality:** a != b tries !(a == b) and !(b == a); a == b tries b == a.
    - **Tie-breakers:** Ordinary candidates beat rewritten ones, and non-reversed beat reversed.
    - **bool required:** A rewritten == chosen for != or reversed == must return bool.
  - **C++20 breakage:** Reversed candidates appeared in old code without warning.
    - **Non-const member ==:** Normal and reversed candidates each win one argument, so C++20 calls it ambiguous.
    - **P2468 escape hatch:** A matching operator!= in the same scope stops that == from being rewritten or reversed.
    - **No == from <=>:** A hand-written <=> never provides ==, because equality can often be cheaper.
  - **Library helpers:** Function objects and exposition-only helpers built on <=>.
    - **compare_three_way:** Calls <=> and gives a strict total order over pointers.
    - **synth-three-way:** Used by pair, tuple and containers; falls back on < and yields weak_ordering.
    - **strong_order:** Gives floating point the IEEE total order, so NaNs have a place.

## Standardese Quiz Questions

### Question 1 [warmup] ([over.match.oper], [class.compare.default])

In C++23, is this program well-formed?

```cpp
#include <compare>

struct P {
  int x;
  auto operator<=>(const P& o) const { return x <=> o.x; }
};

int main() {
  P a{1}, b{1};
  return a == b;
}
```

A. Well-formed: `a == b` is rewritten as `(a <=> b) == 0`
B. Well-formed: a user-declared `operator<=>` implicitly declares `operator==`
C. Ill-formed: there is no `operator==` for `P`
D. Ill-formed: `operator<=>` with a deduced return type must be defaulted

**Answer (C):** Ill-formed: there is no `operator==` for `P`

**Why:** Equality is never rewritten in terms of `<=>`; the rewritten candidates for `==` are only reversed `operator==` functions. An `operator==` is implicitly declared only when `operator<=>` is *defaulted* and no `operator==` is declared, and this one is hand-written. A deduced `auto` return type is fine on a user-written `<=>`.

### Question 2 [warmup] ([over.match.oper], [class.eq])

In C++20 and later, what does `main` return?

```cpp
struct Q {
  int x;
  bool operator==(const Q&) const = default;
};

int main() {
  Q a{1}, b{2};
  return a != b;
}
```

A. 0
B. Nothing: ill-formed, because `Q` has no `operator!=`
C. Nothing: ill-formed, because `!=` needs a defaulted `operator<=>`
D. 1

**Answer (D):** 1

**Why:** Since C++20, `a != b` considers the rewritten candidate `!(a == b)`. The defaulted `operator==` compares `x` memberwise, giving false, so `a != b` is true and `main` returns 1. In C++17 this would have been ill-formed, which is the tempting answer; `operator<=>` plays no part in `!=`.

### Question 3 [warmup] ([expr.spaceship], [cmp.partialord])

What does this program print?

```cpp
#include <compare>
#include <cstdio>
#include <cmath>

int main() {
  double n = std::nan("");
  auto r = n <=> 1.0;
  std::printf("%d %d %d %d\n", r < 0, r == 0, r > 0,
              r == std::partial_ordering::unordered);
}
```

A. `0 0 1 0`
B. `0 0 0 1`
C. `1 0 0 0`
D. Nothing: `<=>` on a NaN is undefined behavior

**Answer (B):** `0 0 0 1`

**Why:** Built-in `<=>` on floating-point operands yields `std::partial_ordering`, and when either operand is a NaN the result is `unordered`. An unordered value compares false against literal zero with every relational operator and with `==`, so the first three are 0 and only the comparison with `unordered` is 1. There is no undefined behaviour; partial ordering exists precisely to represent this case.

### Question 4 [tricky] ([expr.spaceship], [dcl.init.list])

In C++23, what happens with this declaration?

```cpp
#include <compare>

auto r = -1 <=> 1u;
```

A. It is ill-formed
B. `r` is `std::strong_ordering::less`
C. `r` is `std::strong_ordering::greater`, because `-1` converts to a large unsigned value
D. `r` is `std::weak_ordering::less`

**Answer (A):** It is ill-formed

**Why:** For arithmetic operands, `<=>` applies the usual arithmetic conversions, and [expr.spaceship] makes the program ill-formed if a narrowing conversion is needed, other than integral to floating point. Converting `-1` to `unsigned int` is narrowing. The third option is what `-1 < 1u` effectively does, which is exactly the trap `<=>` was designed to reject.

### Question 5 [tricky] ([class.spaceship], [class.compare.default])

Is this program well-formed?

```cpp
#include <compare>

struct Legacy {
  int v;
  bool operator<(const Legacy& o) const { return v < o.v; }
  bool operator==(const Legacy& o) const { return v == o.v; }
};

struct W {
  Legacy l;
  auto operator<=>(const W&) const = default;
};

int main() {
  W a{{1}}, b{{2}};
  return a < b;
}
```

A. Well-formed: the defaulted `<=>` synthesizes a result from `<` and `==`
B. Well-formed: `a < b` falls back to `Legacy::operator<` directly
C. Ill-formed: the defaulted `operator<=>` is defined as deleted, and `a < b` uses it
D. Ill-formed: a class without `<=>` cannot be a member of a class that defaults `<=>`

**Answer (C):** Ill-formed: the defaulted `operator<=>` is defined as deleted, and `a < b` uses it

**Why:** With a deduced `auto` return type, a defaulted `operator<=>` needs `<=>` on every member; `Legacy` has none, so the function is defined as deleted. Declaring the class is fine, but `a < b` selects the deleted function through the rewritten candidate. The fallback to `==` and `<` only happens when the return type is named, such as `std::weak_ordering`, which is why the first option is tempting.

### Question 6 [tricky] ([class.spaceship], [cmp.common])

What is `decltype(M{} <=> M{})`?

```cpp
#include <compare>

struct M {
  int i;
  double d;
  auto operator<=>(const M&) const = default;
};
```

A. `std::strong_ordering`, from the first member
B. `std::weak_ordering`
C. `std::partial_ordering`
D. `auto`; the type is not fixed until the comparison is evaluated

**Answer (C):** `std::partial_ordering`

**Why:** A defaulted `operator<=>` with an `auto` return type returns the common comparison category of its member comparisons. `int <=> int` is `std::strong_ordering` and `double <=> double` is `std::partial_ordering`, and the common category is the weakest, `std::partial_ordering`. The first member does not decide the type, even though it is compared first.

### Question 7 [standardese] ([cmp.categories], [cmp.weakord], [cmp.strongord])

Which of these declarations is ill-formed?

A. `std::partial_ordering p = std::strong_ordering::less;`
B. `std::weak_ordering w = std::strong_ordering::equal;`
C. `std::partial_ordering q = std::weak_ordering::greater;`
D. `std::strong_ordering s = std::weak_ordering::equivalent;`

**Answer (D):** `std::strong_ordering s = std::weak_ordering::equivalent;`

**Why:** The comparison category types convert implicitly only towards weaker guarantees: `strong_ordering` to `weak_ordering` and `partial_ordering`, and `weak_ordering` to `partial_ordering`. Turning a weak ordering into a strong one would claim that equivalent values are interchangeable, so no conversion exists. The other three are all permitted widenings.

### Question 8 [standardese] ([over.match.oper], [expr.spaceship])

Only one comparison function exists. Which expression does the compiler evaluate for `42 < s`, and what is printed?

```cpp
#include <compare>
#include <cstdio>

struct S {
  int v;
  std::strong_ordering operator<=>(int x) const {
    std::puts("member");
    return v <=> x;
  }
};

int main() {
  S s{5};
  std::printf("%d\n", 42 < s);
}
```

A. `(42 <=> s) < 0`; prints `member` then `0`
B. `0 < (s <=> 42)`; prints `member` then `0`
C. `0 < (s <=> 42)`; prints `member` then `1`
D. None: the program is ill-formed because `int` has no `operator<=>(S)`

**Answer (B):** `0 < (s <=> 42)`; prints `member` then `0`

**Why:** For `x < y`, [over.match.oper] adds the rewritten candidate `(x <=> y) < 0` and the reversed candidate `0 < (y <=> x)`. Only the reversed form matches the member, so `42 < s` becomes `0 < (s <=> 42)`. Since 5 is less than 42, `s <=> 42` is `less`, and `0 < less` is false, so it prints `member` and `0`. The third option forgets that the reversal also flips which side of zero the result is tested on.

# Function parameters and default arguments

> A function's type is built from its adjusted parameter types, so arrays become pointers and top-level const disappears, while default arguments stay outside the type and are bound to the declaration a call happens to see.

- **Source:** C++ Atlas (https://cppatlas.com/topics/function-parameters-and-default-arguments)
- **Track:** Expressions and functions
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [dcl.fct] (https://eel.is/c++draft/dcl.fct), [dcl.fct.default] (https://eel.is/c++draft/dcl.fct.default), [dcl.ambig.res] (https://eel.is/c++draft/dcl.ambig.res), [expr.call] (https://eel.is/c++draft/expr.call), [conv.prom] (https://eel.is/c++draft/conv.prom), [conv.fpprom] (https://eel.is/c++draft/conv.fpprom), [cstdarg.syn] (https://eel.is/c++draft/cstdarg.syn), [except.spec] (https://eel.is/c++draft/except.spec), [conv.fctptr] (https://eel.is/c++draft/conv.fctptr), [over.over] (https://eel.is/c++draft/over.over), [class.mem] (https://eel.is/c++draft/class.mem)
- **cppreference links:** [Function declaration](https://en.cppreference.com/w/cpp/language/function), [Default arguments](https://en.cppreference.com/w/cpp/language/default_arguments), [Variadic arguments](https://en.cppreference.com/w/cpp/language/variadic_arguments), [Pointer declaration (pointers to functions)](https://en.cppreference.com/w/cpp/language/pointer), [Address of an overloaded function](https://en.cppreference.com/w/cpp/language/overloaded_address)
- **Prerequisites:** implicit-conversions, initialization-forms, inheritance-and-virtual-functions

## The one idea

A function declaration does two separate jobs. It fixes the function's **type**, which is the return type, the parameter-type-list, and since C++17 whether it is `noexcept`. And it may attach **default arguments**, which are not part of the type at all but a property of that particular declaration.

Almost every surprise in this area comes from mixing the two up. The type is computed after the compiler has rewritten your parameter declarations, so what you wrote is not always what the function takes. Default arguments are substituted by the caller, at compile time, using whatever declaration the call can see and whatever static type the call goes through.

> **Mental model.** The type decides which function you have and what pointers to it look like. Default arguments are a caller-side convenience, pasted in by the compiler from the declaration in view.

## Parameter types are adjusted

[dcl.fct] rewrites each parameter type before the function type is formed. A parameter of type "array of `T`" becomes "pointer to `T`". A parameter of function type becomes a pointer to function. Then top-level `const` and `volatile` are dropped. The resulting list is the parameter-type-list, and it alone determines whether two declarations name the same function.

```cpp
#include <type_traits>

void f(const int a[10]);   // the 10 is ignored; the element const is kept
void f(const int* a);      // redeclares the same function

void g(const int n);       // top-level const is dropped from the type
void g(int n) { n = 1; }   // the definition: n is modifiable here

void h(int callback(int)); // a pointer to function, as if int (*callback)(int)

static_assert(std::is_same_v<decltype(f), void(const int*)>);
static_assert(std::is_same_v<decltype(g), void(int)>);
```

Only the outermost array bound is lost, so `int m[][4]` becomes `int (*)[4]` and the inner bound is part of the type. A reference to an array is not adjusted, which is how `template <std::size_t N> void f(int (&a)[N])` recovers the length. Top-level `const` on a parameter in a definition is legal and only affects the body; repeating it in the header is noise. This also means `sizeof` on an array parameter yields the size of a pointer, which compilers warn about.

## Default arguments are bound at the declaration

A default argument is an expression stored with the declaration. Its names are looked up and bound where the declaration appears, but the expression is evaluated anew at every call that uses it.

```cpp
#include <cstdio>

int level = 1;
void report(int v = level) { std::printf("%d\n", v); }

void demo() {
  int level = 2;   // ignored: the default was bound to ::level
  (void)level;
  ::level = 3;
  report();        // prints 3: ::level is read at the call
}
```

Because the expression is evaluated in the caller's context but bound in the declaration's, the standard restricts what it may name. A default argument may not use `this` or a local variable, and another parameter may not appear in it as a potentially-evaluated expression. That last rule still allows unevaluated uses, so `void f(int a, int b = sizeof(a));` is valid.

```cpp
// void f(int a, int b = a);   // ill-formed: parameter used in a default argument
```

Member functions have one extra freedom. A default argument of a member function declared inside a class is a complete-class context, like a member function body, so it is parsed only after the whole class has been seen and may name members declared later. It still may not use a non-static data member in an evaluated way, because that would need `this`.

```cpp
struct Buffer {
  void resize(int n = default_size);   // OK: default_size is declared below
  static constexpr int default_size = 16;
  int width = 4;
  // void grow(int n = width);         // ill-formed: would need this
  void grow(int n = sizeof(width));    // OK: unevaluated operand
};
```

### Accumulating across declarations

For a non-template function, later declarations in the same scope may add default arguments, but only for parameters to the right of which every parameter already has one, and they may never repeat a default, not even with the same value.

```cpp
#include <cstdio>

void f(int, int);
void f(int, int = 2);    // adds a default for the second parameter
void f(int = 1, int);    // now the first may have one too
// void f(int, int = 2); // ill-formed: redefines a default argument
void f(int a, int b) { std::printf("%d %d\n", a, b); }

void demo() { f(); }     // prints 1 2
```

A declaration in a different scope starts a fresh set. A block-scope declaration of the same function can give it entirely different defaults, visible only in that block. The standard allows it; style guides do not.

> **Standardese.** [dcl.fct.default] says that for non-template functions, default arguments can be added in later declarations of a function in the same scope, and that declarations in different scopes have completely distinct sets of default arguments. Member functions of class templates are stricter: their default arguments must appear on the initial declaration inside the class template.

## Default arguments and virtual functions

Because the caller substitutes the default, it uses the declaration found through the static type of the call. A virtual call still dispatches to the final overrider, but it receives the default argument of the function named by the static type.

```cpp
#include <cstdio>

struct Base {
  virtual void show(int n = 1) const { std::printf("Base %d\n", n); }
  virtual ~Base() = default;
};
struct Derived : Base {
  void show(int n = 2) const override { std::printf("Derived %d\n", n); }
};

void demo() {
  Derived d;
  const Base& b = d;
  b.show();   // prints Derived 1: body from Derived, default from Base
  d.show();   // prints Derived 2
}
```

> **Pitfall.** Never give an override a different default argument. Either repeat the base default or, better, remove defaults from virtual functions and provide a non-virtual wrapper that supplies them.

The same reasoning explains why default arguments vanish through pointers. A pointer to function has only a type, and the type has no defaults, so `void (*p)(int) = report;` must be called with an argument. `std::function` behaves the same way.

## Variadic functions and default argument promotions

A C-style variadic function declares `...` after its named parameters. Arguments that match the ellipsis have no parameter type to convert to, so [expr.call] applies a fixed set of conversions instead: lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions, then the **default argument promotions**. Integer types narrower than `int`, including `bool`, `char` and `short`, are promoted to `int` or `unsigned int`, unscoped enumerations are promoted, and `float` becomes `double`. `std::nullptr_t` becomes `void*`.

```cpp
#include <cstdarg>

double sum(int n, ...) {
  va_list ap;
  va_start(ap, n);
  double s = 0;
  for (int i = 0; i < n; ++i) {
    s += va_arg(ap, double);   // must name the promoted type
  }
  va_end(ap);
  return s;
}

double demo() { float f = 1.5f; return sum(2, f, 2.5); }   // 4: f arrived as double
```

Asking `va_arg` for `float`, `char` or `short` is undefined behaviour, because no argument of that type can arrive. Passing a scoped enumeration, or a class type with a non-trivial copy constructor, move constructor or destructor, through `...` is conditionally-supported with implementation-defined semantics, so do not rely on it. C++ also allows a function with only an ellipsis, `void f(...)`, which overload resolution ranks below every other conversion; that is why it serves as a catch-all in detection idioms. C++26 deprecates writing the ellipsis without a preceding comma, as in `void f(int...)`, because it is easily confused with a parameter pack. Variadic templates, covered in variadic-templates-and-fold-expressions, are the type-safe replacement.

## Declarations that look like objects

[dcl.ambig.res] resolves an ambiguity between a declaration and an expression statement in favour of the declaration. When an initializer in parentheses could be read as a parameter list, it is.

```cpp
struct Timer {};
struct Widget { explicit Widget(Timer) {} int size() const { return 1; } };

void demo() {
  Widget w(Timer());   // declares a function w taking a pointer to function returning Timer
  // w.size();         // ill-formed: w is a function, not an object
  Widget v{Timer{}};   // braces cannot form a parameter list: an object
  (void)v;
}
```

The same rule makes `std::string s();` a function declaration and `int x(int(y));` a declaration of `x` taking an `int` named `y`. Braced initialization, an extra pair of parentheses around the argument, or `=` all force the object reading. The broader choice between initialization syntaxes is the subject of initialization-forms.

## The function type: noexcept, qualifiers and pointers

Since C++17, `noexcept` is part of the function type. A pointer to a `noexcept` function converts implicitly to a pointer to a potentially-throwing one, but not the other way, because that would promise something the function does not. You still cannot overload on `noexcept` alone, and every declaration of a function must agree on its exception specification. The noexcept topic covers what the specifier promises at run time.

```cpp
void may_throw() {}
void no_throw() noexcept {}

void (*p)() = no_throw;               // OK: drops the guarantee
// void (*q)() noexcept = may_throw;  // ill-formed: would add a guarantee
```

For member functions, cv-qualifiers and ref-qualifiers are also part of the type, as described in member-functions-and-this.

A function name converts to a pointer to function, so `p = f` and `p = &f` mean the same thing, and calling through `p(1)`, `(*p)(1)` or even `(**p)(1)` all work, because dereferencing gives back a function lvalue that decays again. When the name is overloaded, the target type chooses: `void (*ph)(double) = h;` selects `h(double)` from the set, under the rules of [over.over]. Since C++20, the standard library says that taking the address of most standard library functions is unspecified or ill-formed, so pass a lambda instead of `&std::toupper`.

## What to remember

- The function type is formed from adjusted parameters: arrays and functions become pointers, and top-level cv-qualifiers are dropped.
- Only the outermost array bound is lost; references to arrays keep their bound.
- Default arguments are not part of the type: they are bound by name at the declaration and evaluated at each call.
- A default argument cannot use `this`, locals, or other parameters in evaluated contexts.
- Later declarations in the same scope may add defaults right to left but never repeat one; other scopes get a fresh set.
- A virtual call uses the default from the static type and the body from the dynamic type.
- Arguments passed to `...` undergo default argument promotions; `va_arg` must name the promoted type.
- If something can be read as a function declaration, it is; braces avoid the most vexing parse.
- Since C++17 `noexcept` is in the type, and pointers convert only from `noexcept` to potentially-throwing.

## Concept Map Outline

- **Parameters and default arguments:** The function type comes from adjusted parameters; default arguments live on declarations, outside the type.
  - **Parameter adjustment:** Parameter types are rewritten before the function type is formed.
    - **Arrays become pointers:** const int a[10] is const int*; only the outermost bound is lost.
    - **Functions become pointers:** A parameter int cb(int) means int (*cb)(int).
    - **Top-level cv dropped:** void f(const int) and void f(int) declare the same function.
    - **Array references kept:** int (&a)[N] keeps the bound, so templates can deduce N.
  - **Default arguments:** Caller-side expressions attached to a declaration.
    - **Bound at declaration:** Names are looked up where the declaration appears.
    - **Evaluated per call:** The expression runs again at every call that uses it.
    - **Forbidden names:** No this, no locals, and no other parameter in a potentially-evaluated use.
    - **Accumulation:** Later declarations in the same scope may add defaults right to left, never repeat one.
    - **Other scopes:** A block-scope redeclaration gets a completely separate set of defaults.
  - **Defaults and dispatch:** Defaults come from what the caller sees, not what runs.
    - **Virtual functions:** The default comes from the static type, the body from the final overrider.
    - **Function pointers:** A pointer's type has no defaults, so every argument must be passed.
  - **Variadic functions:** Arguments matching ... get fixed conversions instead of parameter types.
    - **Default promotions:** bool, char and short become int; float becomes double; nullptr_t becomes void*.
    - **va_arg type:** Must name the promoted type; va_arg(ap, float) is undefined behaviour.
    - **Non-trivial classes:** Passing them or scoped enums through ... is conditionally-supported.
    - **Missing comma:** C++26 deprecates void f(int...) without a comma before the ellipsis.
  - **Most vexing parse:** Anything that can be a declaration is a declaration.
    - **Widget w(Timer()):** Declares a function taking a pointer to function returning Timer.
    - **Fixes:** Use braces, extra parentheses around the argument, or = initialization.
  - **Function type:** Return type, parameter-type-list, noexcept, and member qualifiers.
    - **noexcept since C++17:** Pointers convert from noexcept to potentially-throwing, never back.
    - **Overloaded addresses:** The target type picks the overload when taking an overloaded function's address.
    - **Standard library:** Since C++20, forming pointers to most std functions is unspecified or ill-formed.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.fct.default], [class.virtual])

What does this program print?

```cpp
#include <cstdio>

struct Base {
  virtual void hi(int n = 1) const { std::printf("Base %d\n", n); }
  virtual ~Base() = default;
};
struct Der : Base {
  void hi(int n = 2) const override { std::printf("Der %d\n", n); }
};

int main() {
  Der d;
  const Base& b = d;
  b.hi();
  d.hi();
}
```

A. `Der 2`, then `Der 2`
B. `Base 1`, then `Der 2`
C. `Der 1`, then `Der 2`
D. Ill-formed: an override cannot change a default argument

**Answer (C):** `Der 1`, then `Der 2`

**Why:** The call through `b` is virtual, so `Der::hi` runs, but default arguments are supplied by the caller from the declaration found through the static type, which is `Base::hi` with default 1. The call through `d` sees `Der::hi` and its default 2. Changing a default in an override is legal, merely confusing.

### Question 2 [warmup] ([dcl.ambig.res], [dcl.fct])

Is this program well-formed?

```cpp
struct Timer {};
struct Widget {
  Widget(Timer) {}
  int size() const { return 1; }
};

int main() {
  Widget w(Timer());
  return w.size();
}
```

A. Well-formed: `w` is a `Widget` built from a value-initialized `Timer`, and `main` returns 1
B. Well-formed, but the `Timer` temporary dangles
C. Ill-formed: `Timer()` cannot be used as a constructor argument
D. Ill-formed: `w` declares a function, so `w.size()` is invalid

**Answer (D):** Ill-formed: `w` declares a function, so `w.size()` is invalid

**Why:** [dcl.ambig.res] resolves anything that can be a declaration as a declaration. `Timer()` can be read as a parameter of type "function returning `Timer`", adjusted to a pointer to function, so `w` is a function declaration. Member access on a function is ill-formed. Writing `Widget w{Timer{}};` or `Widget w((Timer()));` gives the object the first option describes.

### Question 3 [warmup] ([dcl.fct])

What is `decltype(f)`?

```cpp
void f(const int a[10]);
```

A. `void(const int[10])`
B. `void(const int*)`
C. `void(int*)`
D. `void(const int* const)`

**Answer (B):** `void(const int*)`

**Why:** A parameter of type "array of `const int`" is adjusted to "pointer to `const int`", and the bound 10 is discarded. The `const` applies to the elements, so it survives; only top-level cv-qualifiers on the parameter itself are removed, and there are none here. A reference-to-array parameter would have kept the bound.

### Question 4 [tricky] ([dcl.fct.default])

What does this program print?

```cpp
#include <cstdio>

int x = 1;
void show(int a = x) { std::printf("%d\n", a); }

int main() {
  int x = 2;
  (void)x;
  ::x = 3;
  show();
}
```

A. `1`: the default is evaluated when `show` is declared
B. `2`: the default is evaluated in the caller's scope
C. `3`
D. Ill-formed: a default argument cannot name a variable

**Answer (C):** `3`

**Why:** The name `x` in the default argument is looked up where `show` is declared, so it means `::x`, not the local `x` in `main`. But the expression is evaluated at each call that uses it, and by then `::x` is 3. Default arguments may name variables with static storage duration; only locals, `this` and, in evaluated contexts, other parameters are forbidden.

### Question 5 [tricky] ([dcl.fct.default])

Is this program well-formed, and if so what does it print?

```cpp
#include <cstdio>

void f(int, int);
void f(int, int = 2);
void f(int = 1, int);
void f(int a, int b) { std::printf("%d %d\n", a, b); }

int main() { f(); }
```

A. Ill-formed: `void f(int = 1, int)` gives a default to a parameter followed by one without
B. Well-formed; prints `1 2`
C. Ill-formed: default arguments must all appear on the first declaration
D. Ill-formed: the definition must repeat the default arguments

**Answer (B):** Well-formed; prints `1 2`

**Why:** For a non-template function, later declarations in the same scope may add default arguments. By the third declaration the second parameter already has a default from a previous declaration, so giving the first one a default is allowed; the right-to-left rule counts defaults from earlier declarations too. The definition must not repeat a default, and here it does not. The first option would be correct if the second declaration were missing.

### Question 6 [tricky] ([conv.fctptr], [except.spec], [dcl.fct])

In C++23, which line makes this translation unit ill-formed?

```cpp
void f() {}
void g() noexcept {}

void (*p1)() = f;            // #1
void (*p2)() = g;            // #2
void (*p3)() noexcept = f;   // #3
void (*p4)() noexcept = g;   // #4
```

A. #2: a `noexcept` function cannot be stored in a plain function pointer
B. #3
C. #4: `noexcept` cannot appear in a pointer declarator
D. None: `noexcept` is not part of the function type

**Answer (B):** #3

**Why:** Since C++17, `noexcept` is part of the function type. The function pointer conversion goes only from pointer-to-`noexcept`-function to pointer-to-potentially-throwing function, which makes #2 valid. #3 would claim that `f` never throws, so no conversion exists and it is ill-formed. The last option describes C++14.

### Question 7 [standardese] ([expr.call], [conv.fpprom], [cstdarg.syn])

What does the standard say about this program?

```cpp
#include <cstdarg>
#include <cstdio>

double sum(int n, ...) {
  va_list ap;
  va_start(ap, n);
  double s = 0;
  for (int i = 0; i < n; ++i) s += va_arg(ap, double);
  va_end(ap);
  return s;
}

int main() {
  float f = 1.5f;
  std::printf("%g\n", sum(2, f, 2.5));
}
```

A. Undefined behavior: a `float` is passed but read as `double`
B. Implementation-defined: the output depends on the calling convention
C. Ill-formed: a `float` cannot be passed to an ellipsis
D. It prints `4`

**Answer (D):** It prints `4`

**Why:** An argument with no corresponding parameter undergoes the default argument promotions, and `float` is promoted to `double` before the call. So both variadic arguments really are `double`, and `va_arg(ap, double)` reads them correctly, giving 4. Reading with `va_arg(ap, float)` would be the undefined behaviour the first option describes.

### Question 8 [standardese] ([dcl.fct.default])

What does this program print?

```cpp
#include <cstdio>

void f(int n = 7);

void g() {
  void f(int n = 9);
  f();
}

void f(int n) { std::printf("%d\n", n); }

int main() {
  f();
  g();
}
```

A. `7`, then `9`
B. `7`, then `7`
C. `9`, then `9`
D. Ill-formed: the block-scope declaration redefines a default argument

**Answer (A):** `7`, then `9`

**Why:** [dcl.fct.default] says declarations in different scopes have completely distinct sets of default arguments. The block-scope declaration in `g` is in a different scope from the namespace-scope one, so giving it a different default is not a redefinition, and calls inside `g` see 9. Calls in `main` see only the namespace-scope declaration and get 7.

# Structured bindings

> A structured binding declaration creates one hidden variable from the initializer and then introduces names that refer into it. The specifiers you write apply to the hidden variable, and the names are aliases, not new variables.

- **Source:** C++ Atlas (https://cppatlas.com/topics/structured-bindings)
- **Track:** Expressions and functions
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [dcl.struct.bind] (https://eel.is/c++draft/dcl.struct.bind), [dcl.type.decltype] (https://eel.is/c++draft/dcl.type.decltype), [expr.prim.lambda.capture] (https://eel.is/c++draft/expr.prim.lambda.capture), [class.temporary] (https://eel.is/c++draft/class.temporary), [tuple.helper] (https://eel.is/c++draft/tuple.helper)
- **cppreference links:** [Structured binding declaration](https://en.cppreference.com/w/cpp/language/structured_binding), [std::tuple_size](https://en.cppreference.com/w/cpp/utility/tuple_size), [std::tuple_element](https://en.cppreference.com/w/cpp/utility/tuple_element)
- **Prerequisites:** type-deduction-auto-decltype, reference-binding-and-temporaries, value-categories

## The one idea

`auto [a, b] = expr;` looks like it declares two variables. It declares one. The compiler invents a variable, which the standard calls `e`, initializes it from `expr` exactly as `auto e = expr;` would, and then makes `a` and `b` names for parts of `e`.

Every rule follows from that picture. The `auto`, `const`, `&` or `&&` you write decide the type of `e`, not of `a` and `b`. Copying happens once, when `e` is initialized, or not at all if `e` is a reference. And `a` and `b` are not objects in their own right: they are names that the compiler resolves to subobjects of `e`, or, for tuple-like types, to references initialized from `get`.

```text
auto& [k, v] = entry;

    entry ----------------+
                          |   e is declared as  auto& e = entry;
    e (hidden, auto&) ----+
      .first  <-- k       k and v name members of e,
      .second <-- v       so they name members of entry
```

> **Mental model.** Rewrite `cv auto ref [names...] = expr;` as `cv auto ref e = expr;` and then read each name as "the i-th part of `e`". Any question about copies, constness or lifetime is a question about `e`.

## What the specifiers apply to

Because the declaration of `e` is formed from your specifiers and initializer, the familiar `auto` deduction rules apply to it, and they explain the common forms:

- `auto [a, b] = p;` copies `p` into `e`. Writing to `a` changes the copy.
- `auto& [a, b] = p;` makes `e` an lvalue reference to `p`. Writing to `a` changes `p`. It does not compile if `p` is a prvalue, because a non-const lvalue reference cannot bind to it.
- `const auto& [a, b] = make();` makes `e` a reference to const bound to the temporary; the names are read-only.
- `auto&& [a, b] = expr;` makes `e` a forwarding reference: it binds to anything without copying.

```cpp
#include <utility>

std::pair<int, int> make() { return {1, 2}; }

void demo() {
  std::pair<int, int> p{1, 2};
  auto  [a, b] = p;     a = 10;   // p.first is still 1: e is a copy
  auto& [c, d] = p;     c = 10;   // p.first is now 10: e refers to p
  // auto& [x, y] = make();       // ill-formed: lvalue reference to a prvalue
  const auto& [x, y] = make();    // OK: e binds to the temporary
  (void)b; (void)d; (void)x; (void)y;
}
```

The one exception to "`e` is declared exactly like `auto e = expr`" is a plain array with no reference qualifier: `e` becomes an array of the same type, and its elements are copied from the source elements one by one. Ordinary `auto` would have decayed the array to a pointer.

## Three ways to bind

Which protocol is used depends only on `E`, the type of `e` with references removed, and the checks happen in this order.

**Arrays.** If `E` is an array type, the names refer to its elements, and their number must equal the array bound.

**Tuple-like types.** Otherwise, if `std::tuple_size<E>` is a complete type with a member named `value`, the tuple protocol is used. The number of names must equal `std::tuple_size<E>::value`. For each index `i`, the compiler introduces a hidden variable of type "reference to `std::tuple_element<i, E>::type`", initialized from `e.get<i>()` if `E` has a member function template `get` whose first template parameter is a non-type parameter, and from `get<i>(e)` found by argument-dependent lookup otherwise. The name then refers to the object that reference is bound to. This is how `std::pair`, `std::tuple` and `std::array` decompose.

**Data members.** Otherwise, `E` must be a non-union class whose non-static data members are all direct members of `E` or all members of the same unambiguous base class, with no anonymous unions. The names refer to the members in declaration order, and the number of names must match. Since C++20 the members only need to be accessible at the point of the declaration, so a friend or member function can decompose a class with private data.

```cpp
class Point {
  int x_ = 1, y_ = 2;
  friend int sum(const Point& p) { auto [x, y] = p; return x + y; }  // OK since C++20
};

// auto [x, y] = Point{};   // ill-formed outside the class: x_ and y_ are private
```

> **Pitfall.** Specializing `std::tuple_size` for a type switches it to the tuple protocol even if it is an aggregate whose members would otherwise bind directly. A half-finished specialization, with `tuple_size` but no working `get`, turns a working declaration into a compile error.

## Names, not variables

A structured binding is an alias, and the language treats it differently from a variable in several observable ways.

**`decltype`.** Applied to an unparenthesized binding, `decltype` gives its *referenced type*, not the type of a reference. For arrays that is the element type, for data members it is the member's declared type with `e`'s cv-qualification added, and for the tuple protocol it is `std::tuple_element<i, E>::type`. So `auto& [a, b] = p;` for a `std::pair<int, int>` gives `decltype(a)` equal to `int`, not `int&`. Parenthesize it, as `decltype((a))`, and you get the expression rule: `a` is an lvalue, so `int&`.

**References inside the element type.** For `std::tie(x, y)`, the element types are `int&`, so the bindings refer to `x` and `y` themselves, even with plain `auto`. The object that `auto` creates is a tuple of references, not a copy of the referenced ints.

```cpp
#include <tuple>

void demo() {
  int x = 1, y = 2;
  auto [a, b] = std::tie(x, y);   // e is a std::tuple<int&, int&>
  a = 10;                          // x is now 10
  (void)b;
}
```

**Bit-fields.** A binding can name a bit-field, which no reference can, because the binding is not a reference. `auto& [flags] = s;` followed by `flags = 2;` writes the bit-field `s.flags`.

**Lambda capture.** In C++17 a structured binding could not be captured by a lambda at all, because it is not a variable. C++20 allows capturing bindings both by copy and by reference, although a binding that names a bit-field still cannot be captured by reference. GCC already accepted such captures in C++17 mode as an extension, while older Clang releases rejected them in every mode.

```cpp
#include <utility>

int demo() {
  auto [a, b] = std::pair{1, 2};
  return [a, &b] { return a + b; }();   // OK since C++20
}
```

C++20 also allowed the `static` and `thread_local` specifiers on a structured binding declaration. `constexpr`, `inline` and `extern` were still not permitted in C++23.

## Lifetime through bindings

Lifetime extension works through `e`. When `e` is a reference bound directly to a temporary, as in `const auto& [a, b] = make();` or `auto&& [a, b] = make();`, the temporary lives as long as `e`, which is the end of the enclosing scope. The names never dangle in that case.

```cpp
#include <cstdio>
#include <utility>

struct Noisy { ~Noisy() { std::puts("~Noisy"); } };
std::pair<Noisy, int> make() { return {}; }

void demo() {
  {
    const auto& [n, i] = make();
    std::puts("body");        // prints before ~Noisy: the pair is still alive
    (void)n; (void)i;
  }                           // ~Noisy here, when e goes out of scope
}
```

The usual limits of lifetime extension still apply. If the initializer is a function call that returns a reference into a temporary, such as a member function that returns `*this` by reference called on a prvalue, then `e` binds to the returned reference, no temporary is bound directly, and the bindings dangle at the end of the full-expression. The rules are the subject of reference-binding-and-temporaries.

## Writing a tuple-like type

To opt a type into the tuple protocol, specialize `std::tuple_size` and `std::tuple_element`, and provide `get<I>` either as a member function template or as a free function template that argument-dependent lookup can find. Free `get` must be in the type's own namespace; a `get` declared elsewhere and visible only through ordinary lookup is not considered.

```cpp
#include <cstddef>
#include <utility>

namespace geo {
struct Pt { int x, y; };
template <std::size_t I> int get(const Pt& p) { return I == 0 ? p.x : p.y; }
}

template <> struct std::tuple_size<geo::Pt> : std::integral_constant<std::size_t, 2> {};
template <std::size_t I> struct std::tuple_element<I, geo::Pt> { using type = int; };

int demo() { auto [a, b] = geo::Pt{3, 4}; return a * b; }   // 12, via geo::get
```

The hidden variable is passed to `get` as an lvalue when `e` is an lvalue reference and as an xvalue otherwise, so a `get` overload set that distinguishes `&` and `&&` can move elements out of a by-value `e`. `std::tuple_element` should be specialized for the unqualified type; the standard library provides the partial specializations for `const E` that make `const auto [a, b]` work.

> **Standardese.** [dcl.struct.bind] says the member `get` is used when class member access lookup for `get` in `E` finds at least one function template whose first template parameter is a non-type parameter. Otherwise `get<i>(e)` is used with `get` looked up by argument-dependent lookup only.

## C++26 additions

C++26 extends the syntax in four ways. GCC 16 implements all of them in `-std=c++26` mode.

- **Attributes on individual bindings** (P0609): `auto [a, b [[maybe_unused]]] = f();`.
- **Structured binding as a condition** (P0963): `if (auto [ok, value] = parse(s))`. The condition is `e` contextually converted to `bool`, and that test is performed before the bindings are initialized, so a tuple-like type's `get` is not called before the check.
- **Binding packs** (P1061): one name may be preceded by `...` to introduce a pack, as in `auto [head, ...tail] = t;`. A pack may only be introduced inside a template, and it can be empty.
- **`constexpr` and `constinit`** (P2686) are now allowed on the declaration, subject to the usual constant-initialization rules.

```cpp
#include <tuple>

template <class T>
int sum_all(const T& t) {
  auto [...xs] = t;          // C++26: xs is a pack of all the elements
  return (0 + ... + xs);
}

int demo() { return sum_all(std::tuple{1, 2, 3}); }   // 6
```

The placeholder name `_`, which can be repeated in one declaration since C++26, also works in structured bindings and is described with the other C++26 language changes.

## What to remember

- A structured binding declaration declares one hidden variable `e`; the names refer into it.
- `auto`, `const`, `&` and `&&` apply to `e`. `auto` copies, `auto&` aliases an lvalue, `const auto&` and `auto&&` bind anything.
- The protocol is chosen in order: array, then tuple-like if `std::tuple_size<E>` is complete, then public or accessible data members.
- The tuple protocol prefers a member `get` template and otherwise uses ADL-only `get<i>(e)`.
- `decltype(name)` gives the referenced type, such as `int` for a `std::pair<int, int>` binding even with `auto&`.
- `auto [a, b] = std::tie(x, y);` still aliases `x` and `y`.
- Bindings can name bit-fields and, since C++20, can be captured by lambdas.
- A reference `e` bound directly to a temporary extends its lifetime; a reference returned from a function does not.
- C++26 adds per-binding attributes, bindings as conditions, packs inside templates, and `constexpr`.

## Concept Map Outline

- **Structured bindings:** One hidden variable e is initialized from the expression; the names refer into it.
  - **The hidden variable e:** Specifiers and ref-qualifiers you write declare e, not the names.
    - **auto:** e is a copy of the initializer, so writes through the names do not reach the source.
    - **auto&:** e aliases an lvalue; it cannot bind to a prvalue.
    - **const auto& and auto&&:** e binds to anything, including temporaries, without copying.
    - **Array exception:** Without a reference, an array initializer is copied element by element into an array e.
  - **Three protocols:** Chosen in order from E, the type of e without references.
    - **Array:** Names refer to elements; their count must equal the bound.
    - **Tuple-like:** Used whenever std::tuple_size<E> is complete with a value member.
    - **Data members:** All non-static members, accessible at the declaration since C++20, in one class.
  - **Names, not variables:** A binding is an alias with its own rules.
    - **decltype:** Gives the referenced type: int for a pair<int, int> binding even with auto&.
    - **std::tie:** Element types are references, so plain auto still aliases the tied variables.
    - **Bit-fields:** A binding can name a bit-field, which no reference can.
    - **Lambda capture:** Forbidden in C++17, allowed in C++20; bit-field bindings cannot be captured by reference.
    - **Specifiers:** static and thread_local since C++20; constexpr only from C++26; never inline.
  - **Lifetime:** Extension works through e, not through the names.
    - **Direct binding extends:** const auto& [a, b] = make(); keeps the temporary alive to scope end.
    - **Returned references dangle:** If the initializer returns a reference into a temporary, nothing is extended.
  - **Tuple protocol:** Specialize tuple_size and tuple_element and provide get.
    - **Member get first:** Used if member lookup finds a get template whose first parameter is a non-type parameter.
    - **ADL-only free get:** Otherwise get<i>(e) is found only by argument-dependent lookup.
    - **Value category of e:** e is passed as an lvalue if it is an lvalue reference, else as an xvalue.
  - **C++26 additions:** Implemented by GCC 16 in -std=c++26 mode.
    - **Per-binding attributes:** auto [a, b [[maybe_unused]]] = f(); attaches an attribute to one name.
    - **As a condition:** if (auto [ok, v] = f()) tests e as bool before the bindings are initialized.
    - **Binding packs:** auto [h, ...t] = x; introduces a possibly empty pack, only inside templates.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.struct.bind])

What does this program print?

```cpp
#include <cstdio>
#include <utility>

struct S { int v = 1; };

int main() {
  std::pair<S, int> p;
  auto [a, b] = p;
  a.v = 5;
  std::printf("%d\n", p.first.v);
  auto& [c, d] = p;
  c.v = 7;
  std::printf("%d\n", p.first.v);
}
```

A. `5`, then `7`
B. `1`, then `7`
C. `1`, then `1`
D. `5`, then `5`

**Answer (B):** `1`, then `7`

**Why:** `auto [a, b] = p;` declares a hidden variable `auto e = p;`, which is a copy, and `a` names `e.first`, so the write does not reach `p`. With `auto&`, the hidden variable is a reference to `p`, so `c` names `p.first` and the second write is visible. The first option assumes bindings always alias the initializer, which is only true when the hidden variable is a reference.

### Question 2 [warmup] ([dcl.struct.bind], [dcl.init.ref])

Is this program well-formed?

```cpp
#include <utility>

std::pair<int, int> make() { return {1, 2}; }

int main() {
  auto& [a, b] = make();
  return a + b;
}
```

A. Well-formed: structured bindings always extend the lifetime of the initializer
B. Well-formed, but `a` and `b` dangle after the declaration
C. Ill-formed: the hidden variable is a non-const lvalue reference initialized from a prvalue
D. Ill-formed: structured bindings cannot have a reference qualifier

**Answer (C):** Ill-formed: the hidden variable is a non-const lvalue reference initialized from a prvalue

**Why:** The declaration introduces `auto& e = make();`, and a non-const lvalue reference cannot bind to a prvalue, so the program is ill-formed. Lifetime extension would apply if the binding were allowed, which is why `const auto&` and `auto&&` work. Reference qualifiers on structured bindings are perfectly legal.

### Question 3 [warmup] ([dcl.struct.bind], [class.access])

Is this program well-formed?

```cpp
class P {
  int x = 1;
public:
  int y = 2;
};

int main() {
  auto [a, b] = P{};
  return a + b;
}
```

A. Ill-formed: `x` is not accessible in `main`
B. Well-formed: only public members are bound, so `a` is `y`
C. Ill-formed, but only because `P` is not an aggregate
D. Well-formed: structured bindings ignore access control

**Answer (A):** Ill-formed: `x` is not accessible in `main`

**Why:** With no `std::tuple_size` specialization, the names bind to all non-static data members of `P` in declaration order, and every one of them must be accessible at the point of the declaration. `x` is private and `main` is not a friend, so the program is ill-formed. Private members are not skipped, and aggregate status is irrelevant: binding to members does not use aggregate initialization.

### Question 4 [tricky] ([dcl.type.decltype], [dcl.struct.bind])

What is `decltype(a)` after this declaration?

```cpp
#include <utility>

std::pair<int, int> p{1, 2};
auto& [a, b] = p;
```

A. `int&`
B. `const int&`
C. `int&&`
D. `int`

**Answer (D):** `int`

**Why:** `std::pair` uses the tuple protocol, and `decltype` of an unparenthesized structured binding is its referenced type, `std::tuple_element<0, std::pair<int, int>>::type`, which is `int`. The `&` makes the hidden variable a reference, but it does not change the referenced type. `int&` is what `decltype((a))` gives, because the parenthesized form uses the rule for lvalue expressions.

### Question 5 [tricky] ([dcl.struct.bind], [tuple.creation])

What does this program print?

```cpp
#include <cstdio>
#include <tuple>

int main() {
  int x = 1, y = 2;
  auto [a, b] = std::tie(x, y);
  a = 10;
  std::printf("%d %d\n", x, y);
}
```

A. `1 2`: plain `auto` copies, so `a` is independent
B. `10 2`
C. Nothing: ill-formed, because `std::tie` returns a prvalue
D. Nothing: undefined behavior, because the tuple is a destroyed temporary

**Answer (B):** `10 2`

**Why:** `std::tie(x, y)` returns `std::tuple<int&, int&>`, and `auto` makes the hidden variable a tuple of that type. It holds references to `x` and `y`, so `std::tuple_element<0, E>::type` is `int&` and `a` refers to `x` itself. `auto` produces a new tuple, not new ints, and since the hidden variable is an object rather than a reference to the temporary, nothing dangles.

### Question 6 [tricky] ([class.temporary], [dcl.struct.bind])

What does this program print?

```cpp
#include <cstdio>
#include <utility>

struct Noisy { ~Noisy() { std::puts("~Noisy"); } };
std::pair<Noisy, int> make() { return {}; }

int main() {
  {
    const auto& [n, i] = make();
    std::puts("body");
    (void)n; (void)i;
  }
  std::puts("after");
}
```

A. `~Noisy`, `body`, `after`: the temporary dies at the end of the declaration
B. `body`, `after`, `~Noisy`
C. `body`, `~Noisy`, `after`
D. Undefined behavior: `n` and `i` refer into a destroyed temporary

**Answer (C):** `body`, `~Noisy`, `after`

**Why:** The hidden variable is `const auto& e = make();`, a reference bound directly to the prvalue, so the temporary pair has its lifetime extended to that of `e`, the end of the inner block. `body` is printed while the pair is alive, then `~Noisy` at the closing brace, then `after`. The first and last options assume the bindings themselves would need to extend the lifetime; they do not, because `e` already does.

### Question 7 [standardese] ([dcl.struct.bind], [tuple.helper])

Both a member `get` and a free `get` exist. What does this program print?

```cpp
#include <cstddef>
#include <cstdio>
#include <utility>

namespace geo {
struct Pt {
  int x, y;
  template <std::size_t I> int get() const { std::puts("member"); return I == 0 ? x : y; }
};
template <std::size_t I> int get(const Pt& p) { std::puts("free"); return I == 0 ? p.x : p.y; }
}

template <> struct std::tuple_size<geo::Pt> : std::integral_constant<std::size_t, 2> {};
template <std::size_t I> struct std::tuple_element<I, geo::Pt> { using type = int; };

int main() {
  auto [a, b] = geo::Pt{3, 4};
  std::printf("%d %d\n", a, b);
}
```

A. `free`, `free`, `3 4`
B. Ill-formed: the call to `get` is ambiguous
C. `3 4` only: `Pt` is an aggregate, so its data members are bound directly
D. `member`, `member`, `3 4`

**Answer (D):** `member`, `member`, `3 4`

**Why:** Because `std::tuple_size<geo::Pt>` is complete, the tuple protocol is used, not direct member binding. [dcl.struct.bind] then uses `e.get<i>()` whenever member lookup for `get` finds a function template whose first template parameter is a non-type parameter, and only otherwise falls back to `get<i>(e)` found by argument-dependent lookup. The two are never put into one overload set, so there is no ambiguity, and the member is called once per binding.

### Question 8 [standardese] ([dcl.struct.bind])

In C++23, which of these structured binding declarations at block scope is well-formed?

A. `constexpr auto [a, b] = std::pair{1, 2};`
B. `static auto [a, b] = std::pair{1, 2};`
C. `inline auto [a, b] = std::pair{1, 2};`
D. `extern auto [a, b] = std::pair{1, 2};`

**Answer (B):** `static auto [a, b] = std::pair{1, 2};`

**Why:** C++20 allowed the storage class specifiers `static` and `thread_local` on structured binding declarations, alongside `auto` and cv-qualifiers. `constexpr` was not permitted until C++26 (P2686); GCC accepts it in C++23 mode only as an extension with a warning, and Clang rejects it. `inline` and `extern` are not allowed in any version.

---

# Track: Classes

Subobject construction order, dynamic dispatch machinery and deterministic RAII.

# Member functions and this

> A non-static member function is an ordinary function with one extra parameter, the object it is called on. Qualifiers, overloading, `this` and C++23's explicit object parameters all follow from taking that parameter seriously.

- **Source:** C++ Atlas (https://cppatlas.com/topics/member-functions-and-this)
- **Track:** Classes
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [class.mfct] (https://eel.is/c++draft/class.mfct), [class.mfct.non.static] (https://eel.is/c++draft/class.mfct.non.static), [over.match.funcs] (https://eel.is/c++draft/over.match.funcs), [expr.prim.this] (https://eel.is/c++draft/expr.prim.this), [dcl.fct] (https://eel.is/c++draft/dcl.fct), [class.mem] (https://eel.is/c++draft/class.mem), [class.static] (https://eel.is/c++draft/class.static), [dcl.inline] (https://eel.is/c++draft/dcl.inline), [expr.prim.lambda.capture] (https://eel.is/c++draft/expr.prim.lambda.capture)
- **cppreference links:** [Non-static member functions](https://en.cppreference.com/w/cpp/language/member_functions), [The this pointer](https://en.cppreference.com/w/cpp/language/this), [Function declaration (explicit object parameter)](https://en.cppreference.com/w/cpp/language/function), [static members](https://en.cppreference.com/w/cpp/language/static)
- **Prerequisites:** value-categories, overload-resolution

## The one idea

A non-static member function is a function with one more parameter than you wrote: the object it is called on. The standard calls it the **object parameter**. For a classic member function it is implicit, and its type is a reference to the class, shaped by the qualifiers after the parameter list. Since C++23 you may also write it out yourself as an **explicit object parameter**, spelled with `this` in front.

Everything else in this topic is a consequence. `const` after the parameter list changes the type of that hidden parameter, so it can be overloaded on. A ref-qualifier says whether the parameter is an lvalue or rvalue reference. A static member function is the case with no object parameter at all, which is why it has no `this`. And `this` itself is just the address of whatever the hidden reference is bound to.

> **Mental model.** Read `int S::get() const &` as `int get(const S& self)`. Overload resolution treats it that way, with a couple of special cases, and so should you.

## The implicit object parameter and cv-qualifiers

For overload resolution, [over.match.funcs] gives every implicit object member function an implicit object parameter. Without a ref-qualifier its type is "lvalue reference to cv `X`", where cv comes from the function's own qualifiers. The object expression, the thing left of the dot, is the implied argument. Calling a non-const member function on a const object therefore fails for the same reason that binding `const S` to `S&` fails, and overloading on `const` is ordinary overloading on the type of a reference parameter.

```cpp
#include <cstdio>

struct Buffer {
  void data()       { std::puts("non-const"); }
  void data() const { std::puts("const"); }
};

void use(Buffer& b, const Buffer& cb) {
  b.data();   // non-const: exact match for Buffer&
  cb.data();  // const: only candidate that binds const Buffer
}
```

Inside the body, `this` is a prvalue whose type is a pointer to the cv-qualified class: `const Buffer*` in the const overload. A `mutable` member escapes that, and so does anything reached through a pointer member, because constness applies to the object's own members and not to what they point at.

There is one exception that the "it is just a reference" picture does not predict. For a member function declared **without** a ref-qualifier, an rvalue may bind to the implicit object parameter even though the parameter is a non-const lvalue reference. That is why `std::string("abc").append("d")` has always compiled.

> **Standardese.** [over.match.funcs] says that for implicit object member functions declared without a ref-qualifier, even if the implicit object parameter is not const-qualified, an rvalue can be bound to it, provided that in all other respects the argument could be converted to its type.

## Ref-qualifiers: overloading on the object's value category

C++11 added `&` and `&&` after the parameter list. With `&` the object parameter is an lvalue reference and the rvalue exception above no longer applies. With `&&` it is an rvalue reference, so the function is only viable on rvalues. The standard library uses this for accessors such as `std::optional::value`, which returns `T&&` when called on an rvalue optional so that the contained value can be moved out.

You cannot mix the two styles freely. If one overload of a name with a given parameter list has a ref-qualifier, an overload with the same object type and no ref-qualifier is ill-formed. Clang rejects such a pair at the declaration; GCC 16 accepts the declarations and reports an ambiguity at the call.

The surprise is inside the body. A ref-qualifier changes which objects you can call the function on, but `*this` is still an lvalue expression, and so is every member you name. Moving out of an rvalue-qualified function needs an explicit cast.

```cpp
#include <cstdio>
#include <string>
#include <utility>

struct Holder {
  std::string name = "x";
  static void sink(std::string&)  { std::puts("lvalue"); }
  static void sink(std::string&&) { std::puts("rvalue"); }

  void take() && {
    sink(name);                    // lvalue: a named member is an lvalue
    sink(std::move(*this).name);   // rvalue: member of an xvalue is an xvalue
  }
};

int main() { Holder{}.take(); }    // prints lvalue, then rvalue
```

## Explicit object parameters (C++23)

P0847, known as "deducing this", lets you declare the object parameter as the first function parameter, prefixed by `this`. The function is then an **explicit object member function**. It is called with the usual `obj.f()` syntax, but inside it there is no `this` pointer and no implicit member access: you must write `self.x`, exactly as in a free function.

```cpp
#include <type_traits>

struct Base {
  template <class Self>
  int which(this Self&&) {
    return std::is_same_v<std::remove_cvref_t<Self>, Base> ? 1 : 2;
  }
};
struct Derived : Base {};

int demo() {
  Derived d;
  Base& b = d;
  return d.which() * 10 + b.which();   // 21: Self deduces from the static type
}
```

The template parameter is deduced from the object expression, so one function template replaces the const, non-const, lvalue and rvalue overloads that accessors used to need. Deduction sees the **static** type of the expression, not the dynamic type, which is why `b.which()` deduces `Base&`. The patterns built on this, such as replacing the curiously recurring template pattern, belong to the topic on CRTP and deducing this.

A few rules keep the feature coherent. An explicit object member function cannot be `static`, `virtual`, or carry cv- or ref-qualifiers, since the parameter type already says all of that. The object parameter may be taken by value, written `this S self`, in which case a call copies or moves the object. And because the function has no hidden parameter left, taking its address gives a plain function pointer.

```cpp
#include <type_traits>

struct E {
  int v = 0;
  int get(this const E& self) { return self.v; }
};

static_assert(std::is_same_v<decltype(&E::get), int (*)(const E&)>);
// not int (E::*)() const: call it as (&E::get)(e)
```

Explicit object parameters also solve recursive lambdas: `[](this auto self, int n) { ... self(n - 1); }` names the closure object without `std::function` or a Y combinator.

## Static members

A static member function has no object parameter, so it has no `this`, cannot be `const` or ref-qualified, and cannot name non-static members without an object. You can still call it as `obj.f()`. For overload resolution, [over.match.funcs] gives it an implicit object parameter that accepts any object, which lets static and non-static overloads compete in one set. C++23 permits `static operator()` and `static operator[]`, so a stateless function object no longer passes an object pointer it never reads.

A static data member is one object shared by the class. Declared in the class without `inline`, it is only a declaration, and an odr-use needs a definition in exactly one translation unit. C++17 added `inline static` data members, which are definitions in the class body, and made every `static constexpr` data member implicitly inline.

```cpp
struct Limits {
  static constexpr int max = 64;   // definition: constexpr implies inline (C++17)
  static const int min = 0;        // declaration only: not inline
  inline static int calls = 0;     // definition (C++17)
};

const int& r = Limits::max;        // OK: odr-use, and a definition exists
// const int& s = Limits::min;     // odr-use with no definition anywhere:
//                                 // ill-formed, no diagnostic required (link error)
```

## Definitions in the class and the complete-class context

A member function defined inside its class definition is implicitly an inline function, per [class.mfct] and [dcl.inline]. That is what lets header-only classes appear in many translation units without violating the one definition rule. The exception is C++20 modules: a member function defined in a class that is attached to a named module is not implicitly inline.

Inside a class, some places are a **complete-class context**: function bodies, default arguments, `noexcept` specifiers and default member initializers. In those places the class is regarded as complete, so names declared later in the class are visible. Everywhere else in the class, ordinary top-to-bottom lookup applies, which bites in return types and parameter types.

```cpp
struct S {
  auto f() noexcept(noexcept(g())) { return g(); }  // OK: body and noexcept
  int g() noexcept { return 1; }                    //     see the later g
  // size_type h();      // error: return type is not a complete-class context
  using size_type = int;
};
```

> **Pitfall.** The fix for the commented line is to move the alias above its first use. Member type aliases are conventionally declared at the top of a class for exactly this reason.

## `this` in lambdas and default member initializers

`this` may appear in the body of an implicit object member function, in its trailing return type and `noexcept` specifier, and in default member initializers, where it points to the object being initialized. A member such as `Node* self = this;` is valid, and later members may read earlier ones, because members are initialized in declaration order.

A lambda in a member function reaches members through the captured `this` pointer. `[this]` captures the pointer, so the lambda refers to the original object and dangles if it outlives it. `[*this]`, added in C++17, copies the whole object into the closure. The default `[=]` used to capture `this` implicitly, which looked like a copy but was a pointer capture; C++20 deprecated that implicit capture, and `[=, this]` became the way to say it explicitly.

```cpp
#include <functional>

struct Counter {
  int n = 0;
  std::function<int()> by_pointer() { return [this]  { return n; }; }
  std::function<int()> by_copy()    { return [*this] { return n; }; }
  std::function<int()> legacy()     { return [=]     { return n; }; }
  // legacy: captures this, not *this; deprecated since C++20
};
```

An explicit object member function has no `this` to capture, so a lambda inside it must capture `self` by reference or by copy like any other parameter.

## What to remember

- A non-static member function has an object parameter; cv- and ref-qualifiers set its type, and overloading on them is ordinary overloading.
- Without a ref-qualifier, rvalues may bind to the implicit object parameter even when it is non-const.
- Inside a `&&`-qualified function, `*this` and named members are still lvalues; use `std::move(*this)`.
- C++23 explicit object parameters deduce from the static type of the object expression and leave no `this`; their address is an ordinary function pointer.
- Static member functions have no `this`; C++23 allows `static operator()` and `static operator[]`.
- `static constexpr` data members are implicitly inline since C++17; plain `static const` members are not.
- In-class member function definitions are implicitly inline, except when attached to a named module.
- Bodies, default arguments, `noexcept` specifiers and default member initializers see the whole class; return and parameter types do not.
- `[this]` captures a pointer, `[*this]` a copy, and implicit `this` capture through `[=]` is deprecated in C++20.

## Concept Map Outline

- **Member functions and this:** A non-static member function takes the object as one extra parameter.
  - **Implicit object parameter:** Overload resolution treats the object as an argument bound to a reference parameter.
    - **cv-qualifiers:** f() const gives the parameter type const X&, so const objects call only const overloads.
    - **Rvalue exception:** Without a ref-qualifier, an rvalue may bind to the non-const implicit object parameter.
    - **this:** A prvalue pointer to the cv-qualified class, pointing at the object parameter.
  - **Ref-qualifiers:** & and && make the object parameter an lvalue or rvalue reference (C++11).
    - **&& accessors:** Let rvalue objects give up their members, as optional::value() && does.
    - ***this stays lvalue:** Inside a && function, *this and named members are lvalues; use std::move(*this).
    - **No mixing:** A ref-qualified overload cannot coexist with an unqualified one for the same object type.
  - **Explicit object parameter:** C++23 deducing this: the object is the first parameter, written with this in front.
    - **No implicit this:** The body has no this pointer; members are reached as self.member.
    - **Static type deduction:** Self deduces from the static type of the object expression, never the dynamic type.
    - **Restrictions:** Cannot be static, virtual, or cv- or ref-qualified.
    - **Plain function pointer:** &S::f has type R(*)(S&...), not a pointer to member.
    - **Recursive lambdas:** [](this auto self, int n) can call self without std::function.
  - **Static members:** Belong to the class, with no object parameter and no this.
    - **Static member functions:** No this, no cv- or ref-qualifiers; still callable as obj.f().
    - **Static call operators:** C++23 allows static operator() and static operator[].
    - **Inline static data:** inline static members (C++17) are defined in the class body.
    - **constexpr implies inline:** static constexpr data members are inline since C++17; static const ones are not.
  - **Class body rules:** Where definitions live and what names they can see.
    - **In-class means inline:** Member functions defined in the class are inline, unless attached to a named module.
    - **Complete-class context:** Bodies, default arguments, noexcept and default member initializers see later members.
    - **Signatures see backwards:** Return and parameter types only see names declared earlier in the class.
  - **this in lambdas:** Lambdas reach members through a captured this.
    - **[this]:** Captures the pointer; the lambda dangles if it outlives the object.
    - **[*this]:** C++17: copies the whole object into the closure.
    - **[=] deprecation:** Implicit this capture through [=] is deprecated in C++20; write [=, this].

## Standardese Quiz Questions

### Question 1 [warmup] ([over.match.funcs], [over.ics.rank])

What does this program print?

```cpp
#include <cstdio>

struct S {
  void f()       { std::puts("plain"); }
  void f() const { std::puts("const"); }
};

void call(const S& s) { s.f(); }

int main() {
  S s;
  call(s);
  s.f();
}
```

A. `plain` then `plain`, because `s` itself is not const
B. `const` then `plain`
C. `const` then `const`
D. Ill-formed: the call through `const S&` is ambiguous

**Answer (B):** `const` then `plain`

**Why:** The object expression in `call` is an lvalue of type `const S`, which can only bind to the implicit object parameter `const S&`, so the const overload runs. In `main`, `s` is a non-const lvalue, and `S&` is a better match than `const S&`, so the plain overload runs. What matters is the type of the expression left of the dot, not the type the object was originally declared with.

### Question 2 [warmup] ([over.match.funcs], [class.temporary])

Is this program well-formed?

```cpp
struct S {
  int n = 0;
  void reset() { n = 0; }
};

int main() {
  S().reset();
}
```

A. Ill-formed: an rvalue cannot bind to the non-const implicit object parameter
B. Well-formed
C. Well-formed, but modifying a temporary is undefined behavior
D. Ill-formed: `reset` would need an `&&` ref-qualifier

**Answer (B):** Well-formed

**Why:** For a member function declared without a ref-qualifier, [over.match.funcs] makes an exception: an rvalue may bind to the implicit object parameter even though its type is a non-const lvalue reference. That is the rule the first option forgets. Modifying a temporary during its lifetime is perfectly defined; the temporary is simply destroyed at the end of the full-expression.

### Question 3 [warmup] ([class.static.data], [dcl.inline], [basic.def.odr])

In C++23, this is the whole program, in one translation unit. Is it well-formed?

```cpp
#include <cstdio>

struct Limits {
  static constexpr int max = 64;
};

int main() {
  const int& r = Limits::max;   // odr-uses Limits::max
  std::printf("%d\n", r);
}
```

A. Ill-formed, no diagnostic required: `max` needs a definition outside the class
B. Well-formed only if the compiler constant-folds `r`
C. Ill-formed: a reference cannot bind to a constexpr variable
D. Well-formed: the in-class declaration is a definition

**Answer (D):** Well-formed: the in-class declaration is a definition

**Why:** Since C++17 a `static constexpr` data member is implicitly an inline variable, so its in-class declaration is a definition and an odr-use such as binding a reference is fine. Before C++17 the first option was correct: binding the reference odr-used `max`, and without an out-of-class definition the program typically failed to link. A plain `static const int` member is still not inline today.

### Question 4 [tricky] ([expr.prim.id.unqual], [expr.prim.this], [over.match.funcs])

What does this program print?

```cpp
#include <cstdio>
#include <string>

struct Holder {
  std::string name = "x";
  static void sink(std::string&)  { std::puts("lvalue"); }
  static void sink(std::string&&) { std::puts("rvalue"); }
  void take() && { sink(name); }
};

int main() { Holder{}.take(); }
```

A. `lvalue`
B. `rvalue`, because `take` only runs on rvalues
C. Ill-formed: the call to `sink` is ambiguous
D. Unspecified: it depends on whether the temporary is materialized

**Answer (A):** `lvalue`

**Why:** The `&&` qualifier only decides which objects `take` may be called on. Inside the body, `name` is an id-expression naming a data member, which is an lvalue, exactly as in any other member function. To get `rvalue` you must write `sink(std::move(name))` or `sink(std::move(*this).name)`.

### Question 5 [tricky] ([class.mem], [basic.scope.class])

Which marked line makes this class definition ill-formed?

```cpp
struct S {
  auto f() noexcept(noexcept(g())) {  // A: noexcept names g
    return g();                        // B: body calls g
  }
  int g() noexcept { return 1; }
  size_type h();                       // C: return type
  using size_type = int;
};
```

A. A, because `g` is not declared yet
B. B, because `g` is not declared yet
C. C, because `size_type` is not declared yet
D. None of them; members are visible throughout the class

**Answer (C):** C, because `size_type` is not declared yet

**Why:** Function bodies, default arguments, `noexcept` specifiers and default member initializers are complete-class contexts, where the whole class is visible, so A and B find the later `g`. A member function's return type is not such a context, so `size_type` is looked up from that point backwards and is not found, so line C is ill-formed. Line A is the tempting answer, but the `noexcept` specifier was made a complete-class context precisely so it can refer to later members.

### Question 6 [tricky] ([dcl.fct], [temp.deduct.call])

What does this C++23 program print?

```cpp
#include <cstdio>
#include <type_traits>

struct Base {
  template <class Self>
  int which(this Self&&) {
    return std::is_same_v<std::remove_cvref_t<Self>, Base> ? 1 : 2;
  }
};
struct Derived : Base {};

int main() {
  Derived d;
  Base& b = d;
  std::printf("%d %d\n", d.which(), b.which());
}
```

A. `2 2`
B. `1 1`
C. Ill-formed: an explicit object parameter cannot be a forwarding reference
D. `2 1`

**Answer (D):** `2 1`

**Why:** `Self` is deduced at compile time from the object expression. `d` has type `Derived`, so `Self` is `Derived&`; `b` has static type `Base`, so `Self` is `Base&`, even though it refers to a `Derived`. Deducing `this` is not a virtual dispatch mechanism, which is why `2 2` is wrong. `this Self&&` is the canonical forwarding form of an explicit object parameter.

### Question 7 [standardese] ([expr.prim.lambda.capture], [depr.capture.this])

In C++20, what does the lambda capture, given that `n` is a non-static data member?

```cpp
struct Counter {
  int n = 0;
  auto get() { return [=] { return n; }; }
};
```

A. A copy of `n`
B. A copy of `*this`
C. The `this` pointer, and this implicit capture is deprecated
D. Nothing: the program is ill-formed because `this` is not listed

**Answer (C):** The `this` pointer, and this implicit capture is deprecated

**Why:** Naming `n` in the lambda means `(*this).n`, so what is implicitly captured is the entity `this`, and it is captured as a pointer even under a copy default. The closure therefore refers to the original object, which is why the first two options are tempting but wrong. C++20 deprecated implicitly capturing `this` through `[=]`; write `[=, this]` or `[*this]` to say which you mean.

### Question 8 [standardese] ([expr.unary.op], [dcl.fct])

In C++23, what is the type of `&E::get`?

```cpp
struct E {
  int v = 0;
  int get(this const E& self) { return self.v; }
};
```

A. `int (E::*)() const`
B. `int (*)(const E&)`
C. `int (E::*)(const E&)`
D. Ill-formed: the address of an explicit object member function cannot be taken

**Answer (B):** `int (*)(const E&)`

**Why:** For an explicit object member function, the object parameter is an ordinary parameter, and [expr.unary.op] says that taking its address yields a pointer to function, not a pointer to member. So the type is `int (*)(const E&)` and you call it as `(&E::get)(e)`. The pointer-to-member type in the first option is what you get for the classic spelling `int get() const`.

# Constructors & Member Initialization Order

> Follow the deterministic sequence of base-class, member, and destructor execution—and avoid initializer reordering traps, virtual dispatch bugs, and accidental non-aggregates.

- **Source:** C++ Atlas (https://cppatlas.com/topics/constructors-and-initialization-order)
- **Track:** Classes
- **Estimated reading time:** 8 minutes
- **ISO C++ clauses:** [class.ctor] (https://eel.is/c++draft/class.ctor), [class.base.init] (https://eel.is/c++draft/class.base.init), [class.dtor] (https://eel.is/c++draft/class.dtor), [class.cdtor] (https://eel.is/c++draft/class.cdtor), [except.ctor] (https://eel.is/c++draft/except.ctor), [dcl.init.aggr] (https://eel.is/c++draft/dcl.init.aggr)
- **cppreference links:** [Constructors and member initializer lists](https://en.cppreference.com/w/cpp/language/initializer_list), [Default constructors](https://en.cppreference.com/w/cpp/language/default_constructor), [Converting constructor](https://en.cppreference.com/w/cpp/language/converting_constructor), [explicit specifier](https://en.cppreference.com/w/cpp/language/explicit), [Destructors](https://en.cppreference.com/w/cpp/language/destructor), [Derived classes](https://en.cppreference.com/w/cpp/language/derived_class)
- **Prerequisites:** initialization-forms, copy-and-move, copy-elision

Every object in C++ follows a single, rigid construction script. Whether a class has one `int` or a diamond inheritance hierarchy, the compiler never follows the order you type in a constructor's member initializer list. Instead, `[class.base.init]/13` locks construction to the **declaration order** in the class definition so that every constructor shares one fixed destruction reverse order.

> **Mental model.** A constructor's member initializer list supplies *arguments*, not *execution order*. Every object is assembled bottom-up—virtual bases, direct bases, declared members, then body—and torn down in the exact mirror sequence when its lifetime ends.

## The invariant initialization order

For any non-delegating constructor of a class `D`, initialization executes in four mandatory stages (`[class.base.init]/13`):

| Phase | Subobjects initialized | Order rule | Destruction order (`~D`) |
| --- | --- | --- | --- |
| 1 | Virtual base classes | Depth-first, left-to-right in the inheritance DAG | Runs **4th** (very last) |
| 2 | Direct non-virtual base classes | Left-to-right in the base-specifier list | Runs **3rd** |
| 3 | Non-static data members | Top-to-bottom declaration order in class body | Runs **2nd** |
| 4 | Constructor compound body `{ ... }` | Statements inside `D::D(...)` | `~D` body runs **1st** (before subobjects) |

Two subtleties stand out in diamond hierarchies. First, **the most-derived class owns every virtual base**: when `Derived` inherits from `Left` and `Right` (which both inherit virtually from `VBase`), `Derived`'s constructor invokes `VBase`'s initializer directly—or default-initializes `VBase` if `Derived` omits it—while `Left` and `Right`'s initializers for `VBase` are skipped completely. Second, if a member has both a default member initializer (`int n = 42;`) and a mem-initializer (`: n(7)`), the mem-initializer wins and the default member initializer is ignored without double work.

```cpp
#include <iostream>

struct VBase {
    explicit VBase(int x) { std::cout << "VBase(" << x << ") "; }
    virtual ~VBase() = default;
};

struct Left : virtual VBase {
    Left() : VBase(1) { std::cout << "Left "; } // VBase(1) skipped by Derived!
};

struct Right : virtual VBase {
    Right() : VBase(2) { std::cout << "Right "; } // VBase(2) skipped by Derived!
};

struct Derived : Left, Right {
    int first = (std::cout << "first ", 10);
    int second;

    // Even if written in reverse order, VBase -> Left -> Right -> first -> second -> body:
    Derived() : VBase(99), Left(), Right(), second(first + 1) {
        std::cout << "Derived\n";
    }
};
```

## The mem-initializer order trap and initialization vs. assignment

Because member order always obeys declaration order inside the class body, reordering members in a mem-initializer list creates silent use-before-initialization bugs.

> **Pitfall.** Writing `struct Buffer { int* data; std::size_t cap; Buffer(std::size_t n) : cap(n), data(new int[cap]) {} };` has undefined behavior. Because `data` is declared before `cap`, `data(new int[cap])` runs *first*, reading an uninitialized `cap` before `cap(n)` executes. Always keep mem-initializers in exact declaration order and enable `-Wreorder`.

Always initialize members in the mem-initializer list rather than assigning inside `{ ... }`. A member constructed in `{ name_ = std::move(s); }` is **default-constructed first** during Phase 3 and then **move-assigned** during Phase 4—wasting work and failing to compile altogether for `const` members, reference members (`T&`), and types without default constructors.

## Delegating constructors and inherited constructors

C++11 added **delegating constructors** so one constructor can forward to another (`Widget() : Widget(0) { ... }`). A delegating constructor cannot mention any base or member in its initializer list—the target constructor owns all of Phases 1 through 3.

Delegating introduces an important exception-handling rule (`[except.ctor]/3`):

- In a **non-delegating** constructor, throwing inside the constructor body unwinds only already-constructed bases and members; the class's own destructor `~Widget()` does *not* run because the object never finished constructing.
- In a **delegating** constructor, the object's lifetime is considered to have **begun as soon as the target constructor returns**. If the delegating constructor's own body throws afterward, `~Widget()` *does* execute during stack unwinding.

You can also pull base-class constructors into a derived class with `using Base::Base;` (`[namespace.udecl]`), which generates matching forwarding constructors in `Derived` while still initializing `Derived`'s own data members via their default member initializers.

## Virtual dispatch during construction and destruction

Inside a base constructor or destructor, the dynamic type of `*this` is temporarily the base class currently executing, never the final derived class (`[class.cdtor]/4`).

> **Standardese.** "When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class's non-static data members, and the object to which the call applies is the object under construction or destruction, the function called is the final overrider in the constructor's or destructor's class and not one overriding it in a more-derived class." — `[class.cdtor]`

That guarantee prevents a base constructor from touching `Derived` member variables whose constructors have not started yet (or whose destructors have already finished). Calling a **pure virtual** function directly (or implicitly without overriding it in the current class) from a constructor or destructor is undefined behavior—pass configuration values as constructor arguments or invoke a two-phase helper after construction instead.

```cpp
struct Base {
    Base() { init_log(); } // Always calls Base::init_log(), never Derived::init_log()!
    virtual const char* kind() const { return "Base"; }
    void init_log() const { (void)kind(); }
    virtual ~Base() = default;
};

struct Derived : Base {
    int payload = 42;
    const char* kind() const override { return "Derived"; }
};
```

## Special rules: explicit, defaulted, and aggregate traps

Three modern constructor rules save subtle diagnostics once you know them:

1. **Mark converting constructors `explicit`.** Any non-explicit constructor callable with one argument acts as an implicit conversion (`void take(Span); take(10);`). Since C++11, `explicit` also blocks copy-list-initialization with multiple arguments (`return {1, 2};`), and C++20 added conditional `explicit(bool)` (`explicit(!std::is_convertible_v<T, U>)`) for wrapper templates like `std::pair` and `std::optional`.
2. **User-declared constructors suppress defaults.** Declaring *any* constructor—even `Widget(int)`—suppresses the implicitly declared default constructor unless you explicitly write `Widget() = default;`.
3. **C++20 tightened aggregate rules.** Prior to C++20, writing `Point() = default;` kept `Point` an aggregate. Starting in C++20 (`[dcl.init.aggr]/1`), **any user-declared constructor**—even `= default` or `= delete`—removes aggregate status, breaking `{1, 2}` aggregate initialization unless you omit the constructor declaration entirely or provide a matching constructor.

```cpp
#include <type_traits>

struct AggregatePoint {
    int x = 0;
    int y = 0;
};

struct NonAggregatePoint {
    int x = 0;
    int y = 0;
    NonAggregatePoint() = default; // User-declared: disables aggregate init in C++20+!
};

static_assert(std::is_aggregate_v<AggregatePoint>);
static_assert(!std::is_aggregate_v<NonAggregatePoint>);

AggregatePoint p1{1, 2}; // Valid aggregate initialization
// NonAggregatePoint p2{1, 2}; // Error in C++20+: no matching constructor
```

## What to remember

- **Declaration order rules construction.** Virtual bases run first, then direct bases left-to-right, then non-static data members top-to-bottom, ignoring mem-initializer order.
- **Destruction is exact LIFO.** Destructors unwind bodies, members, direct bases, and finally virtual bases in strict reverse construction order.
- **Virtual calls stay in the active class.** Inside `Base::Base()` or `Base::~Base()`, `*this` has dynamic type `Base`, never `Derived`.
- **Delegating completes object lifetime early.** Once the target constructor finishes, throwing in the delegating body triggers `~T()`.
- **Watch `explicit` and C++20 aggregates.** Use `explicit` on single- and multi-argument constructors to stop silent conversions, and omit `= default` constructors when you want aggregate brace initialization.

## Concept Map Outline

- **Constructors & Init Order:** Object construction and destruction follow fixed declaration-order phases regardless of initializer list order.
  - **Strict Subobject Sequence:** Every non-delegating constructor assembles subobjects in four rigid standard-mandated phases.
    - **1. Virtual bases first:** The most-derived class initializes all virtual bases once depth-first left-to-right.
    - **2. Direct bases left-to-right:** Non-virtual direct base classes construct in the order listed on the class header.
    - **3. Members in declaration order:** Non-static data members initialize top-to-bottom as declared in the class body.
    - **4. Constructor body runs last:** The compound statement executes only after every base and member has been constructed.
  - **Mem-Initializer Rules:** Member initializer lists supply construction arguments without altering initialization order.
    - **Initializer order is ignored:** Reordering members in a colon list still runs them in declaration order, risking uninitialized reads.
    - **Init beats body assignment:** Initializing members directly avoids default-constructing then reassigning and handles const or ref fields.
    - **Default member initializers:** Inline member initializers serve as fallbacks skipped whenever a mem-initializer names that member.
  - **Destruction & Exceptions:** Teardown mirrors construction in reverse and handles partially built or delegated objects carefully.
    - **Exact reverse teardown:** Destructors run their body first, then members, direct bases, and virtual bases in reverse.
    - **Partial build unwinds subobjects:** Throwing in a non-delegating constructor destroys built subobjects without calling ~Class().
    - **Delegating completes lifetime:** Once a target constructor finishes, throwing in the delegating body invokes ~Class().
  - **Virtual Dispatch Hazard:** Polymorphic dispatch treats the object under construction or destruction as its current class.
    - **Dynamic type is current class:** Virtual calls inside Base::Base() resolve to Base overriders, never Derived.
    - **Pure virtual call is UB:** Invoking an unimplemented pure virtual during construction or destruction causes undefined behavior.
  - **Special & Aggregate Rules:** Constructor declarations govern implicit conversions, default generation, and C++20 aggregate eligibility.
    - **explicit stops silent conversions:** Use explicit and C++20 explicit(bool) to prevent unwanted scalar or braced conversions.
    - **User ctor drops default:** Declaring any custom constructor suppresses the implicitly generated default constructor.
    - **C++20 aggregate restriction:** Any user-declared constructor, even = default, disqualifies a type from aggregate initialization.

## Standardese Quiz Questions

### Question 1 [warmup] ([class.base.init])

Why does `Buffer(std::size_t n) : cap(n), data(new int[cap]) {}` exhibit undefined behavior?

```cpp
struct Buffer {
    int* data;
    std::size_t cap;
    Buffer(std::size_t n) : cap(n), data(new int[cap]) {}
};
```

A. `new int[cap]` cannot appear inside a member initializer list.
B. `std::size_t` cannot be converted inside an initializer list.
C. `data` is declared before `cap`, so `data` initializes first and reads an uninitialized `cap`.
D. Member initializer lists evaluate strictly right-to-left.

**Answer (C):** `data` is declared before `cap`, so `data` initializes first and reads an uninitialized `cap`.

**Why:** Under `[class.base.init]/13`, non-static data members always initialize in declaration order inside the class body (`data`, then `cap`), ignoring the order written in the colon initializer list. `data(new int[cap])` reads indeterminate `cap` before `cap(n)` runs.

### Question 2 [warmup] ([class.base.init])

When constructing a `std::string` member `name_` from a parameter, why should you prefer `: name_(std::move(s))` over `name_ = std::move(s);` in the constructor body?

A. The member initializer constructs `name_` once in place instead of default-constructing it first and then move-assigning.
B. Assignment inside a constructor body is forbidden for standard library types.
C. `std::move` only works inside member initializer lists.
D. Member initializers skip calling `~std::string()` at destruction.

**Answer (A):** The member initializer constructs `name_` once in place instead of default-constructing it first and then move-assigning.

**Why:** Every member not named in the mem-initializer list is initialized before entering the constructor body (`[class.base.init]/9`), so assigning inside `{ ... }` performs default construction followed by assignment. Mem-initializers construct once directly and are mandatory for `const`, reference, and non-default-constructible members.

### Question 3 [tricky] ([class.cdtor])

Given `Base::Base()` calling `virtual const char* kind() const`, what does `Derived d;` cause `Base::Base()` to observe when `Derived` overrides `kind()`?

```cpp
struct Base {
    Base() { std::cout << kind(); }
    virtual const char* kind() const { return "Base"; }
    virtual ~Base() = default;
};
struct Derived : Base {
    const char* kind() const override { return "Derived"; }
};
Derived d;
```

A. "Derived", because the vptr already points to `Derived`'s vtable.
B. Undefined behavior whenever any virtual function is called from a constructor.
C. Compile error: virtual functions cannot be called inside constructors.
D. "Base", because during `Base::Base()` the dynamic type of the object is `Base`.

**Answer (D):** "Base", because during `Base::Base()` the dynamic type of the object is `Base`.

**Why:** Under `[class.cdtor]/4`, while a base constructor or destructor is executing, the object's dynamic type is that base class (`Base`), not the still-uninitialized `Derived` class. Virtual dispatch resolves to `Base::kind()`.

### Question 4 [tricky] ([class.base.init])

In a virtual-inheritance diamond `struct Derived : Left, Right`, where `Left() : VBase(1)` and `Right() : VBase(2)` and `Derived() : Left(), Right()` omits `VBase`, how is `VBase` initialized?

```cpp
struct VBase { VBase(int x = 0); };
struct Left : virtual VBase { Left() : VBase(1) {} };
struct Right : virtual VBase { Right() : VBase(2) {} };
struct Derived : Left, Right { Derived() : Left(), Right() {} };
```

A. `VBase(1)` runs via `Left`, and `Right`'s `VBase(2)` is skipped.
B. `Derived` acts as the most-derived class and default-initializes `VBase(0)`, ignoring both `Left` and `Right`'s `VBase` initializers.
C. Compile error: `Derived` must explicitly repeat `VBase(1)` or `VBase(2)`.
D. `VBase` is constructed twice—once with `1` and once with `2`.

**Answer (B):** `Derived` acts as the most-derived class and default-initializes `VBase(0)`, ignoring both `Left` and `Right`'s `VBase` initializers.

**Why:** `[class.base.init]/7` specifies that virtual base classes are initialized solely by the most-derived class (`Derived`), ignoring `VBase(...)` mem-initializers in intermediate bases `Left` and `Right`. Because `Derived` omitted `VBase`, `VBase` is default-initialized with `0`.

### Question 5 [standardese] ([except.ctor])

If a delegating constructor finishes calling its target constructor and then throws inside its own compound body `{ ... }`, does `~Widget()` execute?

```cpp
struct Widget {
    Widget(int) {}
    Widget() : Widget(0) { throw 1; }
    ~Widget();
};
```

A. No; `~Widget()` never executes if any constructor throws.
B. Only if `Widget(int)` was marked `noexcept`.
C. Yes; once the target constructor completes, the object's lifetime has begun so `~Widget()` runs during unwinding.
D. Undefined behavior unless caught inside a function-try-block.

**Answer (C):** Yes; once the target constructor completes, the object's lifetime has begun so `~Widget()` runs during unwinding.

**Why:** Unlike a non-delegating constructor (where throwing destroys only constructed subobjects), `[except.ctor]/3` states that an object whose constructor delegates is considered fully constructed once the target constructor returns normally. Therefore throwing in the delegating body invokes `~Widget()`.

### Question 6 [standardese] ([dcl.init.aggr])

Why does `Point p{1, 2};` fail to compile in C++20 and C++23 when `Point` declares `Point() = default;`?

```cpp
struct Point {
    int x;
    int y;
    Point() = default;
};
Point p{1, 2};
```

A. `= default` makes `Point` trivial rather than initializable with braces.
B. In C++20+, any user-declared constructor—even `= default` or `= delete`—disqualifies a class from being an aggregate.
C. Aggregate initialization only works when all members have default member initializers.
D. `Point()` must be declared `constexpr` to support `{1, 2}`.

**Answer (B):** In C++20+, any user-declared constructor—even `= default` or `= delete`—disqualifies a class from being an aggregate.

**Why:** Prior to C++20, defaulted or deleted constructors did not prevent a class from being an aggregate. C++20 (`[dcl.init.aggr]/1`) changed the definition so *any* user-declared or inherited constructor makes the class a non-aggregate, leaving `Point p{1, 2}` with no matching two-argument constructor.

# Inheritance and Virtual Functions

> How C++ lays out base subobjects, dispatches virtual calls through vtables, handles multiple and virtual inheritance, and traps callers during construction and destruction.

- **Source:** C++ Atlas (https://cppatlas.com/topics/inheritance-and-virtual-functions)
- **Track:** Classes
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [class.derived] (https://eel.is/c++draft/class.derived), [class.mi] (https://eel.is/c++draft/class.mi), [class.virtual] (https://eel.is/c++draft/class.virtual), [class.abstract] (https://eel.is/c++draft/class.abstract), [class.dtor] (https://eel.is/c++draft/class.dtor), [class.cdtor] (https://eel.is/c++draft/class.cdtor), [class.access.virt] (https://eel.is/c++draft/class.access.virt), [expr.dynamic.cast] (https://eel.is/c++draft/expr.dynamic.cast)
- **cppreference links:** [Derived classes](https://en.cppreference.com/w/cpp/language/derived_class), [virtual function specifier](https://en.cppreference.com/w/cpp/language/virtual), [override specifier](https://en.cppreference.com/w/cpp/language/override), [final specifier](https://en.cppreference.com/w/cpp/language/final), [Abstract class](https://en.cppreference.com/w/cpp/language/abstract_class), [Destructors](https://en.cppreference.com/w/cpp/language/destructor), [dynamic_cast conversion](https://en.cppreference.com/w/cpp/language/dynamic_cast), [Using-declaration](https://en.cppreference.com/w/cpp/language/using_declaration)
- **Prerequisites:** constructors-and-initialization-order, casts-and-qualifiers

Inheritance in C++ serves two distinct purposes: composing object representations by embedding base subobjects, and dispatching behavior dynamically through interfaces. Confusing those two mechanisms—especially how memory layout interacts with compile-time lookup versus runtime dispatch—causes slicing, undefined deletion, and surprising access bugs.

## Base subobjects and object layout

When `Derived` inherits from `Base`, C++ does not allocate `Base` separately and store a hidden heap pointer. Instead, the `Base` subobject lives directly inside the byte footprint of `Derived` (`[class.derived]`). Under single non-virtual inheritance on common ABIs, the base subobject typically starts at offset zero, followed by `Derived`'s own data members.

> **Mental model.** A `Derived` object is a single contiguous block containing one or more embedded `Base` subobjects plus `Derived`'s own members. Passing `Derived` by value to a parameter of type `Base` copies only the `Base` slice and leaves a plain `Base` object behind.

That embedded layout explains **object slicing**. If a function takes `Base b` by value and receives a `Derived`, copy construction initializes `b` strictly from `Derived`'s `Base` subobject; any derived state vanishes, and `b`'s dynamic type becomes `Base`. Polymorphic callers must therefore pass references (`Base&`, `const Base&`) or pointers (`Base*`, `std::unique_ptr<Base>`).

If a base class has no non-static data members and no virtual functions, the **empty base optimization** (EBO) lets the compiler give that base subobject zero size inside `Derived` (provided two bases of the same type do not share an address). Under multiple inheritance (`struct C : A, B`), `C` embeds both `A` and `B` sequentially. Converting a non-null `C*` to `B*` shifts the pointer address forward by `B`'s offset inside `C`, whereas converting a null `C*` preserves `nullptr`.

## Dynamic dispatch, vtables, and override safety

Every expression of class, pointer, or reference type has a **static type** fixed at compile time and—for polymorphic classes declaring or inheriting at least one `virtual` function—a **dynamic type** belonging to the most-derived object currently occupying that storage.

Compilers almost universally implement `virtual` dispatch with two structures: one read-only **vtable** (virtual function table) per polymorphic class holding function pointers and RTTI metadata, and one hidden **vptr** pointer embedded inside each polymorphic object instance pointing to its dynamic class's vtable. Calling `base_ptr->encode(42)` loads the vptr from `*base_ptr`, indexes into the slot assigned to `encode`, and calls the target address.

```cpp
struct Codec {
    virtual ~Codec() = default;
    virtual int encode(int x) const = 0; // pure virtual makes Codec abstract
};

int Codec::encode(int x) const { return x; } // legal out-of-class fallback definition

struct FastCodec final : Codec {
    int encode(int x) const override {
        return x * 2 + Codec::encode(1); // qualified call bypasses vtable dispatch
    }
};
```

Always mark overriding functions `override`. Without `override`, changing a parameter type, omitting `const`, or dropping a `&`/`&&` ref-qualifier silently creates a brand-new unrelated virtual or non-virtual function instead of overriding the base slot. Adding `final` on a class or virtual member seals further overriding and enables the optimizer to devirtualize calls through pointers of that static type. Notice also that a pure virtual function (`= 0`) prevents direct instantiation of `Codec` (`[class.abstract]`), yet may still provide a definition invoked explicitly via qualified syntax (`Codec::encode(1)`).

## Name hiding, using-declarations, and access traps

C++ splits name lookup, access checking, and default arguments from virtual dispatch. Neglecting that split produces two classic surprises.

First, **name hiding** happens during unqualified lookup before overload resolution begins. If `Derived` declares `void log(double)`, that declaration hides *every* overload named `log` in `Base`, including `void log(int)`. Calling `derived.log(42)` silently picks `log(double)` unless `Derived` pulls base overloads into scope with `using Base::log;`.

Second, **access control** (`public`, `protected`, `private`) and **default arguments** on a virtual call are resolved strictly against the **static type** of the call expression (`[class.access.virt]`), while the function body itself is chosen by the **dynamic type**.

```cpp
struct Base {
    virtual void log(int x = 10) const { (void)x; }
    virtual ~Base() = default;
};

struct Derived : Base {
    using Base::log;
    void log(double d) const { (void)d; }
private:
    void log(int x = 99) const override { (void)x; } // private + different default
};

void dispatch(const Base& b) {
    b.log(); // calls Derived::log(10): public via Base, default 10 via Base
}
```

> **Pitfall.** Making an overriding function `private` in `Derived` does not block callers using a `Base&` or `Base*`, and overriding a default argument in `Derived` has zero effect when invoked polymorphically through `Base`. Keep virtual overrides at matching access and avoid default arguments on virtual functions altogether.

The static-versus-dynamic split across every rule of a virtual call is compactly summarized in this lookup matrix:

| Call property | Resolved from | Reason in standard |
| --- | --- | --- |
| Unqualified name lookup | Static type | Scopes checked at compile time |
| Access check (`public`/`private`) | Static type | Checked at call site expression |
| Default argument value | Static type | Substituted at compile time |
| Target function body | Dynamic type | Dispatched via virtual override |

## Virtual destructors and virtual dispatch in constructors

Deleting a derived object through a `Base*` when `Base::~Base()` is non-virtual triggers **undefined behavior** (`[expr.delete]`), not merely an incomplete destructor call. A polymorphic base class designed for owning deletion through base pointers must declare a `public` `virtual` destructor (`virtual ~Base() = default;`). Conversely, a non-polymorphic mixin or base class that forbids deletion via `Base*` should make its destructor `protected` and non-virtual. Note that a pure virtual destructor (`virtual ~Base() = 0;`) still requires a body (`Base::~Base() {}`), because every derived destructor automatically invokes its base destructor during teardown.

Equally critical is what happens while a constructor or destructor runs.

> **Standardese.** Under `[class.cdtor]`, during execution of `Base`'s constructor or destructor, the dynamic type of the object under construction or destruction is `Base`—not `Derived`.

Because `Derived`'s members are not yet constructed during `Base::Base()` (and have already been destroyed before `Base::~Base()`), C++ locks the `vptr` to `Base` while `Base`'s constructor or destructor runs. Calling a virtual function from `Base::Base()` invokes `Base`'s own implementation rather than `Derived`'s override, and calling a pure virtual function without qualification during construction or destruction causes undefined behavior.

## Multiple inheritance, virtual bases, and RTTI

Non-virtual diamond inheritance (`Left : Base`, `Right : Base`, `Join : Left, Right`) places two separate `Base` subobjects inside `Join`, making conversions from `Join*` to `Base*` ambiguous. Inheriting `virtual Base` (`Left : virtual Base`, `Right : virtual Base`) merges them into a single shared subobject, typically accessed at runtime via a compiler-generated offset table inside the vtable.

With virtual inheritance, **the most-derived class initializes every virtual base directly** (`[class.base.init]`). When constructing `Join`, `Join`'s member-initializer list constructs `Base`, and any `Base(...)` initializers written in `Left` or `Right` are skipped entirely—even if `Join` omits `Base(...)` and relies on default initialization.

At runtime, two RTTI operators inspect polymorphic objects whose static type is a base class:

- `dynamic_cast<Target*>(ptr)` walks the dynamic object's RTTI graph safely across **downcasts** (`Base*` to `Derived*`) and **cross-casts** (`Left*` to sibling `Right*` inside `Join`), returning `nullptr` if the cast fails; `dynamic_cast<Target&>(ref)` throws `std::bad_cast` on failure (`[expr.dynamic.cast]`).
- `typeid(*ptr)` evaluates the dynamic `std::type_info` only when `*ptr` is a glvalue of polymorphic class type (`[expr.typeid]`), throwing `std::bad_typeid` if `ptr` is null; for non-polymorphic expressions, `typeid` evaluates only the static type and does not evaluate its operand.

## What to remember

- Inheritance embeds `Base` subobjects inside `Derived`; passing by value slices `Derived` and strips polymorphism.
- Always use `override` on overrides and `final` when sealing interfaces; pure virtuals (`= 0`) can still have definitions.
- Access control, name lookup, and default arguments bind to the **static type**, whereas virtual dispatch selects the **dynamic type**'s overrider.
- Deleting a derived object via a non-virtual base destructor is undefined behavior; make polymorphic base destructors `public virtual` (or non-polymorphic base destructors `protected` non-virtual).
- Inside `Base`'s constructor and destructor, the dynamic type is `Base`, never `Derived`; in virtual inheritance, the most-derived constructor initializes the virtual base directly.

## Concept Map Outline

- **Inheritance & Virtuals:** C++ separates embedded subobject layout and compile-time lookup rules from runtime virtual dispatch.
  - **Object Layout:** Derived objects embed base subobjects contiguously in memory rather than holding hidden heap pointers.
    - **Embedded Base Subobject:** Every Derived instance stores its Base subobjects directly inside its own footprint.
    - **Object Slicing:** Passing Derived by value copies only the Base subobject and resets the dynamic type to Base.
    - **Pointer Adjustment:** Converting a non-null derived pointer to a secondary base shifts the address by that base offset.
    - **Virtual Bases:** Virtual inheritance merges diamond bases into one subobject initialized by the most-derived class.
  - **Virtual Dispatch:** Polymorphic classes select overriders at runtime using the dynamic type rather than the pointer type.
    - **Static vs Dynamic Type:** Expressions carry a fixed compile-time static type while pointers and references point to a dynamic type.
    - **vptr and vtable:** Each polymorphic object holds a vptr pointing to its class vtable of virtual function entries.
    - **override and final:** These specifiers catch signature mismatches at compile time and enable devirtualization.
    - **Pure Virtual Functions:** Marking a virtual function pure makes the class abstract while still allowing a qualified definition.
  - **Lookup & Access:** Name hiding, access specifiers, and default arguments resolve statically before virtual dispatch runs.
    - **Name Hiding:** Declaring any same-named member in Derived hides all Base overloads unless brought in with using.
    - **Static Access Check:** Access rules on a virtual call are enforced against the static type at the call site.
    - **Static Default Args:** Default argument expressions come from the static receiver type even when a derived override executes.
  - **Lifetime Boundaries:** Polymorphic deletion and constructor or destructor execution obey strict dynamic-type boundaries.
    - **Virtual Destructors:** Deleting Derived through a non-virtual Base destructor is undefined behavior rather than a partial free.
    - **Ctor and Dtor Dispatch:** During Base construction or destruction the object's dynamic type is Base, preventing derived dispatch.
  - **RTTI & Casts:** Runtime type identification inspects polymorphic objects for safe downcasts and cross-casts.
    - **dynamic_cast:** Navigates polymorphic hierarchies safely, returning null for invalid pointers or throwing bad_cast for references.
    - **typeid Operator:** Evaluates the dynamic type_info for dereferenced polymorphic pointers and throws bad_typeid on null.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.delete], [class.dtor])

What happens when a caller deletes a Derived object through a Base* pointer whose ~Base() destructor is NOT virtual?

```cpp
struct Base {
    ~Base() {}
};
struct Derived : Base {
    std::string data = "owned";
};
void destroy() {
    Base* p = new Derived{};
    delete p;
}
```

A. Only ~Base() runs and Derived::data leaks, which is otherwise well-defined
B. Both ~Derived() and ~Base() run because operator delete checks heap metadata
C. The behavior is undefined according to [expr.delete]
D. The compiler rejects delete p unless Base has at least one virtual function

**Answer (C):** The behavior is undefined according to [expr.delete]

**Why:** Under [expr.delete], deleting a polymorphic or derived-class object through a base pointer whose static type has a non-virtual destructor is undefined behavior—even if Derived adds no non-trivial data members.

### Question 2 [warmup] ([class.virtual], [dcl.fct])

Why does omitting the override specifier on Derived::render below introduce a subtle bug?

```cpp
struct Widget {
    virtual void render(int dpi) const;
};
struct Button : Widget {
    void render(int dpi);
};
```

A. Button::render lacks const, so it hides Widget::render instead of overriding it
B. Virtual functions cannot be overridden without repeating the virtual keyword
C. The compiler automatically converts Widget::render to non-const to match Button
D. Button becomes an abstract class until override is added

**Answer (A):** Button::render lacks const, so it hides Widget::render instead of overriding it

**Why:** const-qualification is part of a member function's type. Without override, Button::render(int) declares a brand-new unrelated non-virtual member that hides Widget::render(int) const rather than overriding it.

### Question 3 [tricky] ([class.access.virt], [class.virtual])

What is the result of compiling and calling probe()?

```cpp
struct Base {
    virtual int value(int x = 10) const { return x; }
    virtual ~Base() = default;
};
struct Derived : Base {
private:
    int value(int x = 99) const override { return x + 1; }
};
int probe() {
    Derived d;
    const Base& b = d;
    return b.value();
}
```

A. Compile error: Derived::value is private
B. Returns 100 because Derived::value runs with Derived's default argument 99
C. Returns 10 because virtual calls with private overrides fall back to Base
D. Compiles and returns 11: access and default arg use Base, dispatch uses Derived

**Answer (D):** Compiles and returns 11: access and default arg use Base, dispatch uses Derived

**Why:** Access control ([class.access.virt]) and default arguments ([dcl.fct.default]) are checked and substituted statically from Base at the call site b.value(). At runtime, virtual dispatch still invokes Derived::value(10), returning 11.

### Question 4 [tricky] ([class.cdtor])

What does constructing Derived log when Base's constructor calls the virtual function tag()?

```cpp
struct Base {
    Base() { log(tag()); }
    virtual ~Base() = default;
    virtual const char* tag() const { return "Base"; }
};
struct Derived : Base {
    const char* tag() const override { return "Derived"; }
};
```

A. "Derived", because the dynamic type of the full object is already Derived
B. "Base", because inside Base::Base() the object's dynamic type is Base
C. Undefined behavior whenever any virtual function is called from a constructor
D. Compile error: virtual functions cannot be called inside constructors

**Answer (B):** "Base", because inside Base::Base() the object's dynamic type is Base

**Why:** Under [class.cdtor], while Base::Base() executes, Derived's subobject has not started its lifetime yet, so the dynamic type of *this is Base. Virtual dispatch therefore resolves tag() to Base::tag().

### Question 5 [standardese] ([class.base.init], [class.mi])

In virtual diamond inheritance below, what value does Join{}.id hold after construction?

```cpp
struct Common {
    int id;
    explicit Common(int i = 0) : id(i) {}
};
struct Left : virtual Common { Left() : Common(1) {} };
struct Right : virtual Common { Right() : Common(2) {} };
struct Join : Left, Right {
    Join() : Left(), Right() {}
};
```

A. 0, because the most-derived class Join initializes Common and omits Common from its initializer list
B. 1, because Left appears first in Join's base-specifier list
C. 2, because Right overwrites Common after Left runs
D. Ill-formed: Join fails to compile unless it explicitly writes Common(0)

**Answer (A):** 0, because the most-derived class Join initializes Common and omits Common from its initializer list

**Why:** Under [class.base.init], a virtual base subobject is always initialized by the constructor of the most-derived class (Join). Initializers for Common in Left and Right are ignored, so Join default-initializes Common via Common(0).

### Question 6 [standardese] ([class.dtor], [class.abstract])

Why does declaring a pure virtual destructor `virtual ~Stream() = 0;` still require providing an out-of-class body `Stream::~Stream() = default;`?

```cpp
struct Stream {
    virtual ~Stream() = 0;
};
struct FileStream : Stream {};
```

A. Only because linkers always emit vtable slots for destructors even on abstract classes
B. Because pure virtual functions can never have empty bodies in C++
C. Because FileStream's destructor implicitly invokes Stream::~Stream() non-virtually during teardown
D. It is optional unless a caller deletes through Stream*

**Answer (C):** Because FileStream's destructor implicitly invokes Stream::~Stream() non-virtually during teardown

**Why:** Every derived destructor implicitly calls each direct base class's destructor statically (not via virtual dispatch) when tearing down the base subobject ([class.dtor]). Without a definition for Stream::~Stream(), linking FileStream fails.

# Multiple and virtual inheritance

> With several bases, a derived object holds several base subobjects at different addresses, so conversions may move the pointer and names may be ambiguous. Virtual inheritance shares one base subobject among all paths, at the price of most-derived initialization and run-time located bases.

- **Source:** C++ Atlas (https://cppatlas.com/topics/multiple-and-virtual-inheritance)
- **Track:** Classes
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [class.mi] (https://eel.is/c++draft/class.mi), [class.member.lookup] (https://eel.is/c++draft/class.member.lookup), [class.base.init] (https://eel.is/c++draft/class.base.init), [class.virtual] (https://eel.is/c++draft/class.virtual), [conv.ptr] (https://eel.is/c++draft/conv.ptr), [expr.static.cast] (https://eel.is/c++draft/expr.static.cast), [expr.reinterpret.cast] (https://eel.is/c++draft/expr.reinterpret.cast), [expr.dynamic.cast] (https://eel.is/c++draft/expr.dynamic.cast), [basic.compound] (https://eel.is/c++draft/basic.compound), [intro.object] (https://eel.is/c++draft/intro.object), [expr.cast] (https://eel.is/c++draft/expr.cast)
- **cppreference links:** [Derived classes (virtual base classes)](https://en.cppreference.com/w/cpp/language/derived_class), [static_cast conversion](https://en.cppreference.com/w/cpp/language/static_cast), [reinterpret_cast conversion](https://en.cppreference.com/w/cpp/language/reinterpret_cast), [dynamic_cast conversion](https://en.cppreference.com/w/cpp/language/dynamic_cast), [Empty base optimization](https://en.cppreference.com/w/cpp/language/ebo)
- **Prerequisites:** inheritance-and-virtual-functions, constructors-and-initialization-order, casts, object-layout-and-alignment

## The one idea

A class with several bases contains one subobject per non-virtual base, each at its own place inside the object. Converting a pointer from the derived class to a base means finding that subobject, and in general that changes the address. A virtual base is different: however many paths lead to it, the most derived object contains exactly one, shared subobject, whose position is only known at run time.

Most of the rules follow from that picture. Names found in two different subobjects are ambiguous. Casts that know the class relationship adjust pointers, while casts that do not, such as `reinterpret_cast`, do not. And because a shared virtual base belongs to no single path, only the most derived class can initialize it.

> **Mental model.** A pointer to a base is a pointer to a particular subobject, not to the whole object. Any cast that does not know the inheritance graph cannot find the right subobject.

## Several base subobjects and pointer adjustment

Take `struct C : A, B { ... };`. A `C` object contains an `A` subobject and a `B` subobject, and the standard does not say where. Typical implementations put `A` at offset zero and `B` after it, so `static_cast<B*>(&c)`, or the implicit conversion, adds an offset to the address.

The compiler applies the offset in both directions because it knows the class graph. Converting `B*` back to `C*` with `static_cast` subtracts it, and a null pointer stays null in both directions. Comparing a `B*` with a `C*` converts the `C*` to `B*` first, so the comparison is true for the same object even though the raw addresses differ.

```cpp
#include <cstdio>

struct A { int a = 1; };
struct B { int b = 2; };
struct C : A, B { int c = 3; };

int main() {
  C c;
  B* pb = &c;                       // adjusted to the B subobject
  C* p1 = static_cast<C*>(pb);      // adjusted back: p1 == &c
  std::printf("%d %d\n", pb == &c, p1->c);   // 1 3, guaranteed
  // C* p2 = reinterpret_cast<C*>(pb);  // not adjusted: p2 still points at the B
  //                                    // subobject, so p2->c is undefined behavior
}
```

`reinterpret_cast` between object pointer types is specified as a round trip through `void*`. Converting from `void*` only yields a pointer to a different object when the two objects are **pointer-interconvertible**, which a class and its second base are not. So the value is unchanged: a `C*` that points at a `B`. The same trap catches code that stores a `B*` in a `void*` and later casts the `void*` to `C*`. C-style casts are exposed too: when either class is incomplete at the cast, [expr.cast] leaves it unspecified whether the `static_cast` or the `reinterpret_cast` meaning is used.

> **Pitfall.** Round-trip through `void*` only with the exact type you started from. Store a `B*`, get back a `B*`, then `static_cast` to `C*` if you must.

## Ambiguity and name lookup

Member name lookup in a class with several bases looks in each base and merges the results. If the name is found in two different base subobjects, the lookup is ambiguous, and the program is ill-formed when the name is used. This happens **before** overload resolution, so different parameter lists do not help.

```cpp
struct Reader { void put(int) {} };
struct Writer { void put(double) {} };
struct Device : Reader, Writer {
  // using Reader::put; using Writer::put;   // uncomment to overload them
};

void use(Device& d) {
  // d.put(1);          // ill-formed: put is found in two base classes
  d.Reader::put(1);     // OK: qualified name picks the subobject
}
```

Two using-declarations bring both sets into the derived scope, after which ordinary overload resolution applies. Static members, nested types and enumerators found through several paths are not ambiguous when they denote the same entity, because no particular subobject is needed.

## The diamond and virtual base classes

If `Left` and `Right` both derive from `Top`, and `Bottom` derives from both, a `Bottom` contains two `Top` subobjects. Converting `Bottom*` to `Top*` is ambiguous, and a member of `Top` must be reached through `Left::` or `Right::`.

```text
non-virtual                      virtual

  Top     Top                       Top
   |       |                       /   \
  Left   Right                  Left   Right
     \   /                         \   /
     Bottom                        Bottom
two Top subobjects              one shared Top
```

Declaring the base `virtual`, as in `struct Left : virtual Top`, makes all virtual occurrences of `Top` in a most derived object share one subobject. The conversion to `Top*` is then unambiguous, and `Top`'s constructor runs once.

Shared bases also create **dominance**. A name declared in a derived class hides the same name in a base, and with a shared virtual base that holds across paths: if `Left` declares `f` and `Top` declares `f`, then in `Bottom` the name `Left::f` dominates `Top::f`, even though `Right` sees only `Top::f`. With non-virtual inheritance the same shape is ambiguous, because `Right`'s `Top` is a different subobject.

For virtual functions, the final overrider must be unique. If both `Left` and `Right` override a virtual function of a shared `Top`, `Bottom` must override it too, or the class is ill-formed.

## Who initializes a virtual base

Because the shared subobject belongs to no single path, [class.base.init] gives its initialization to the **most derived class**. Mem-initializers naming a virtual base in intermediate classes are ignored when those classes are not the most derived. If the most derived class does not name the virtual base, the virtual base is default-initialized, and the program is ill-formed if it has no default constructor.

```cpp
#include <cstdio>

struct Top { Top(int v) { std::printf("Top %d\n", v); } };
struct Left  : virtual Top { Left()  : Top(1) {} };
struct Right : virtual Top { Right() : Top(2) {} };
struct Bottom : Left, Right {
  Bottom() : Top(3) {}   // required: Top has no default constructor
};

int main() { Bottom b; }   // prints Top 3; Top(1) and Top(2) are ignored
```

Virtual bases are also constructed first, before any non-virtual base, in the order of a depth-first, left-to-right walk of the base class graph. For `struct M : N, L, R` where only `L` and `R` derive virtually from `V`, the constructors run in the order `V`, `N`, `L`, `R`, `M`, and destruction reverses it.

> **Standardese.** [class.base.init] says that a mem-initializer whose mem-initializer-id denotes a virtual base class is ignored during execution of a constructor of any class that is not the most derived class.

## Casts across the graph and empty bases

`static_cast` can convert down from a non-virtual base, unchecked. It cannot convert down from a virtual base, and the program is ill-formed if you try, because the position of the virtual base relative to the derived class is not a compile-time constant. `dynamic_cast` handles that case, and it can also **cross-cast** sideways: given an `A*` that points into a `C : A, B`, `dynamic_cast<B*>` finds the `B` subobject of the same most derived object, or returns null if there is no unique public one. `dynamic_cast<void*>` returns the address of the most derived object. Downcasts, cross-casts and casts to `void*` all need a polymorphic source type.

```cpp
struct A { virtual ~A() = default; };
struct B { virtual ~B() = default; };
struct C : A, B {};

B* sideways(A* pa) {
  return dynamic_cast<B*>(pa);   // non-null when *pa is part of a C
  // static_cast<B*>(pa) is ill-formed: A and B are unrelated
}
```

Empty base classes may occupy no storage, the empty base optimization, which the topic on object layout and alignment covers. Multiple inheritance adds one constraint: two subobjects of the same type must have distinct addresses, per [intro.object]. An empty base cannot share its address with a member or another base of the same type, so the optimization quietly turns off in that case.

## Layout: ABI practice, not the standard

> **Mental model.** Everything in this section is implementation practice under the Itanium C++ ABI used by GCC and Clang on Linux and macOS, not a guarantee. MSVC differs in detail.

The first non-virtual polymorphic base is the **primary base**: it lives at offset zero and shares the object's vptr. Every other polymorphic base subobject has its own vptr pointing into a secondary vtable. When you call a virtual function through a `B*` and `C` overrides it, the `B` vtable slot points to a small **thunk** that subtracts the offset to get `this` back to the start of the `C` before jumping to `C`'s function.

A virtual base sits at an offset that depends on the most derived class, so the vtable stores a **virtual base offset**, and converting to a virtual base loads that offset at run time. During construction, intermediate classes use special construction vtables with offsets that suit the partially built object. MSVC instead stores a separate virtual base table pointer in the object. These differences are why mixing compilers across a class hierarchy needs a shared ABI, and why size or offset numbers are never portable facts.

## What to remember

- Each non-virtual base is its own subobject; converting to most bases changes the pointer value.
- `static_cast` and implicit conversions adjust pointers; `reinterpret_cast` and round trips through `void*` with a different type do not.
- Lookup that finds a name in two base subobjects is ambiguous before overload resolution; qualify it or add using-declarations.
- A non-virtual diamond has two top subobjects; virtual inheritance shares one.
- In a virtual diamond, a derived declaration dominates the virtual base's, and a virtual function needs a unique final overrider.
- Only the most derived class initializes a virtual base; intermediate mem-initializers for it are ignored.
- Virtual bases are built first, depth-first and left to right.
- `static_cast` cannot go down from a virtual base; `dynamic_cast` can, and can cross-cast.
- Two subobjects of the same type never share an address, which can disable the empty base optimization.
- Thunks, primary bases and virtual base offsets are ABI practice, not standard guarantees.

## Concept Map Outline

- **Multiple and virtual inheritance:** One subobject per non-virtual base; one shared subobject per virtual base.
  - **Pointer adjustment:** A base pointer points at a subobject, often at a different address.
    - **static_cast adjusts:** Implicit and static conversions add or subtract the base offset; null stays null.
    - **reinterpret_cast does not:** C* from a second-base B* still points at the B; using it as a C is undefined.
    - **Comparison converts:** pb == &c converts &c to B* first, so it is true for the same object.
    - **void* round trips:** Cast back only to the exact type you stored.
  - **Name lookup:** Lookup merges results from every base before overload resolution.
    - **Ambiguity:** A name found in two different base subobjects is ill-formed to use.
    - **Qualify or using:** d.Reader::put picks one; two using-declarations make them overload.
    - **Same entity is fine:** Static members, types and enumerators found via several paths are not ambiguous.
    - **Dominance:** With a shared virtual base, a derived declaration wins over the base's.
  - **The diamond:** Two paths to the same base class.
    - **Non-virtual:** Two Top subobjects; converting Bottom* to Top* is ambiguous.
    - **Virtual:** One shared Top; its constructor runs once.
    - **Unique final overrider:** If two paths override a shared base's virtual, the most derived must override too.
  - **Virtual base initialization:** The most derived class owns the shared base's construction.
    - **Intermediates ignored:** Mem-initializers for a virtual base run only in the most derived constructor.
    - **Default otherwise:** If the most derived class omits it, the base is default-initialized or ill-formed.
    - **Constructed first:** Virtual bases precede all non-virtual bases, depth-first and left to right.
  - **Casts across the graph:** Which cast can navigate which edge.
    - **No static downcast:** static_cast from a virtual base to a derived class is ill-formed.
    - **dynamic_cast cross-cast:** Moves sideways from A* to B* inside the same most derived object.
    - **dynamic_cast to void*:** Returns the address of the most derived object.
    - **Distinct addresses:** Two subobjects of the same type never share an address, limiting EBO.
  - **Layout (ABI practice):** Itanium ABI details, not standard guarantees.
    - **Primary base:** The first non-virtual polymorphic base sits at offset zero and shares the vptr.
    - **Thunks:** Secondary vtable slots adjust this before jumping to the override.
    - **Virtual base offset:** Stored in the vtable and loaded at run time; MSVC uses a vbptr instead.

## Standardese Quiz Questions

### Question 1 [warmup] ([conv.ptr], [class.mi], [class.member.lookup])

Is this program well-formed?

```cpp
struct Top { int t = 0; };
struct Left  : Top {};
struct Right : Top {};
struct Bottom : Left, Right {};

int main() {
  Bottom b;
  Top* p = &b;
  (void)p;
}
```

A. Well-formed: `p` points to the `Top` inside `Left`, the first base
B. Ill-formed: `Top` is an ambiguous base of `Bottom`
C. Well-formed, but which `Top` is chosen is unspecified
D. Undefined behavior

**Answer (B):** Ill-formed: `Top` is an ambiguous base of `Bottom`

**Why:** Without virtual inheritance, a `Bottom` contains two distinct `Top` subobjects, one through `Left` and one through `Right`. The derived-to-base conversion must identify a unique subobject, so it is ill-formed. There is no rule preferring the first base; write `static_cast<Left*>(&b)` first, or make `Top` a virtual base.

### Question 2 [warmup] ([class.base.init], [class.mi])

What does this program print?

```cpp
#include <cstdio>

struct V { V() { std::puts("V"); } };
struct N { N() { std::puts("N"); } };
struct L : virtual V { L() { std::puts("L"); } };
struct R : virtual V { R() { std::puts("R"); } };
struct M : N, L, R { M() { std::puts("M"); } };

int main() { M m; }
```

A. `N V L R M`
B. `V L V R N M`
C. `N V L V R M`
D. `V N L R M`

**Answer (D):** `V N L R M`

**Why:** The most derived class constructs its virtual bases first, before any non-virtual base, so the single shared `V` comes before `N` even though `N` is listed first. Then the direct bases run in declaration order, `N`, `L`, `R`, and finally the body of `M`. `V` appears once because both paths share one virtual base subobject, which rules out the options with two `V` lines.

### Question 3 [warmup] ([expr.eq], [conv.ptr])

What does this program print?

```cpp
#include <cstdio>

struct A { int a = 1; };
struct B { int b = 2; };
struct C : A, B { int c = 3; };

int main() {
  C c;
  B* pb = &c;
  std::printf("%d\n", pb == &c);
}
```

A. `0`, because `pb` points past the `A` subobject
B. `1`
C. Either `0` or `1`; the layout is implementation-defined
D. Ill-formed: `B*` and `C*` cannot be compared

**Answer (B):** `1`

**Why:** Comparing `B*` with `C*` first converts `&c` to `B*` with the usual derived-to-base pointer conversion, which yields the address of the same `B` subobject `pb` points to. The comparison is therefore true regardless of layout. Converting both to `void*` first would compare raw addresses, and that result does depend on the implementation.

### Question 4 [tricky] ([class.member.lookup], [namespace.udecl])

Is this program well-formed?

```cpp
struct Reader { void put(int) {} };
struct Writer { void put(double) {} };
struct Device : Reader, Writer {};

int main() {
  Device d;
  d.put(1);
}
```

A. Well-formed: overload resolution picks `Reader::put(int)`, the exact match
B. Well-formed: the first base listed wins
C. Ill-formed: the conversion from `Device` to `Writer` is ambiguous
D. Ill-formed: the name `put` is ambiguous

**Answer (D):** Ill-formed: the name `put` is ambiguous

**Why:** Member name lookup runs before overload resolution. It finds `put` in two different base class subobjects, so the lookup result is ambiguous and the program is ill-formed, whatever the argument types. The first option is how people expect overloading to work; it does once `Device` declares `using Reader::put; using Writer::put;`.

### Question 5 [tricky] ([class.base.init])

What does this program print?

```cpp
#include <cstdio>

struct Top { Top(int v) { std::printf("Top %d\n", v); } };
struct Left  : virtual Top { Left()  : Top(1) {} };
struct Right : virtual Top { Right() : Top(2) {} };
struct Bottom : Left, Right { Bottom() : Top(3) {} };

int main() { Bottom b; }
```

A. `Top 1`
B. `Top 1` then `Top 2`
C. `Top 3`
D. Ill-formed: `Top` is initialized by more than one constructor

**Answer (C):** `Top 3`

**Why:** A virtual base is initialized by the most derived class, here `Bottom`, using its mem-initializer `Top(3)`. The mem-initializers `Top(1)` in `Left` and `Top(2)` in `Right` are ignored because those constructors are not running for the most derived object. `Top 1` is the tempting answer for anyone who expects the first base on the path to win.

### Question 6 [tricky] ([expr.reinterpret.cast], [expr.static.cast], [basic.compound])

What does the standard say about this program?

```cpp
#include <cstdio>

struct A { int a = 1; };
struct B { int b = 2; };
struct C : A, B { int c = 3; };

int main() {
  C c;
  B* pb = &c;
  C* p = reinterpret_cast<C*>(pb);
  std::printf("%d\n", p->c);
}
```

A. It prints `3`, the same as with `static_cast`
B. Undefined behavior
C. Ill-formed: `reinterpret_cast` cannot convert between related classes
D. It prints an implementation-defined value

**Answer (B):** Undefined behavior

**Why:** `reinterpret_cast` between object pointers behaves like `static_cast` through `void*`, and that only lands on a different object when the two are pointer-interconvertible. A class is not pointer-interconvertible with its second base, so `p` still points at the `B` subobject, and accessing `p->c` as if it were a `C` is undefined behavior. `static_cast<C*>(pb)` would subtract the base offset and print 3, which is why the first option is tempting. The cast itself compiles.

### Question 7 [standardese] ([class.member.lookup])

What does `run()` return?

```cpp
struct Top   { int f() { return 1; } };
struct Left  : virtual Top { int f() { return 2; } };
struct Right : virtual Top {};
struct Bottom : Left, Right {};

int run() {
  Bottom b;
  return b.f();
}
```

A. 2
B. 1
C. Ill-formed: `f` is ambiguous between `Left::f` and `Top::f`
D. Unspecified: it depends on the order of the base classes

**Answer (A):** 2

**Why:** Lookup in `Bottom` finds `Left::f` through `Left` and `Top::f` through `Right`. Because `Top` is a virtual base, the `Top` subobject seen through `Right` is the same one that is a base of `Left`, so [class.member.lookup] discards `Top::f` in favour of `Left::f`; this is dominance. If `Top` were a non-virtual base, the two declarations would be in unrelated subobjects and the call would be ambiguous, which is why the third option is tempting.

### Question 8 [standardese] ([expr.static.cast], [expr.dynamic.cast])

Which conversion in `down` is ill-formed?

```cpp
struct V { virtual ~V() = default; };
struct W : virtual V {};

void down(V* pv) {
  W* a = dynamic_cast<W*>(pv);   // A
  W* b = static_cast<W*>(pv);    // B
  (void)a; (void)b;
}
```

A. A, because `dynamic_cast` cannot go through a virtual base
B. B, because `static_cast` cannot convert from a virtual base to a derived class
C. Both A and B
D. Neither; both compile, and B is undefined behavior if `*pv` is not a `W`

**Answer (B):** B, because `static_cast` cannot convert from a virtual base to a derived class

**Why:** [expr.static.cast] allows a downcast from `B*` to `D*` only if `B` is neither a virtual base of `D` nor a base of a virtual base of `D`. The offset from a virtual base to the derived class depends on the most derived object, so a static conversion cannot compute it and B is ill-formed. `dynamic_cast` reads it from the object at run time and is well-formed here. The last option describes downcasting from a non-virtual base.

# Access control and friends

> Access control decides whether a name may be used, never which entity a name means. It is checked after lookup and overload resolution, it follows the static type, and friendship grants it one class or function at a time.

- **Source:** C++ Atlas (https://cppatlas.com/topics/access-control-and-friends)
- **Track:** Classes
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [class.access] (https://eel.is/c++draft/class.access), [class.access.general] (https://eel.is/c++draft/class.access.general), [class.access.spec] (https://eel.is/c++draft/class.access.spec), [class.access.base] (https://eel.is/c++draft/class.access.base), [class.friend] (https://eel.is/c++draft/class.friend), [class.protected] (https://eel.is/c++draft/class.protected), [class.access.virt] (https://eel.is/c++draft/class.access.virt), [class.access.nest] (https://eel.is/c++draft/class.access.nest), [class.local] (https://eel.is/c++draft/class.local), [over.match.general] (https://eel.is/c++draft/over.match.general), [basic.lookup.argdep] (https://eel.is/c++draft/basic.lookup.argdep), [temp.deduct.general] (https://eel.is/c++draft/temp.deduct.general), [temp.spec.general] (https://eel.is/c++draft/temp.spec.general)
- **cppreference links:** [Access specifiers](https://en.cppreference.com/w/cpp/language/access), [Friend declaration](https://en.cppreference.com/w/cpp/language/friend), [Derived classes](https://en.cppreference.com/w/cpp/language/derived_class), [Nested classes](https://en.cppreference.com/w/cpp/language/nested_types), [Injected-class-name](https://en.cppreference.com/w/cpp/language/injected-class-name)
- **Prerequisites:** member-functions-and-this, inheritance-and-virtual-functions, name-lookup-and-adl

## The one idea

Access control is a filter applied to **names**, at the very end. The compiler first finds what a name refers to, then picks an overload, and only then asks whether the place that used the name is allowed to use it. If not, the program is ill-formed. Access never makes the compiler look elsewhere or choose a different function.

Three consequences follow, and most surprises in this area are one of them. A private member still hides outer names and still wins overload resolution. Access follows the static type and the name you wrote, not the object you have. And anything that does not spell the name, such as `auto` holding a value of a private nested type, is not checked at all.

> **Mental model.** Lookup decides *what*, overload resolution decides *which*, and access decides only *whether you may say it here*. Access is a permission on a spelling, not a property of the object.

## Access is checked last

A class member is `public`, `protected`, or `private`. Members of a `class` default to private and members of a `struct` or `union` default to public; that default, together with the default access of base classes, is the only difference between `class` and `struct`. Because access comes after overload resolution, a private overload that is the best match is an error, even when a worse public overload would have worked.

```cpp
struct S {
  void f(int);
private:
  void f(double);
};

void g(S& s) {
  // s.f(1.0);  // ill-formed: f(double) is chosen, then found private
  s.f(1);       // OK: f(int) is the best match and is public
}
```

Lookup ignores access too. A private member in a base class hides a global of the same name, so the derived class gets an access error instead of the global.

```cpp
int x;
class B { int x; };
struct D : B {
  void f() { ::x = 1; }  // must qualify: plain x finds B::x, which is private
};
```

Access applies to names, not to types or objects. A function may return a private nested type, and a caller can hold the result with `auto` and use its public members, because the private name is never spelled. Virtual functions follow the same rule: [class.access.virt] says access is checked on the expression used for the call, using the naming class of the static type. A public virtual in the base may be overridden by a private function in the derived class, and a call through a base reference reaches it.

```cpp
#include <cstdio>
struct B { virtual void f() { std::puts("B"); } };
class D : public B { void f() override { std::puts("D"); } };

void call(D& d) {
  B& b = d;
  b.f();    // OK, prints D: access checked on B::f
  // d.f(); // ill-formed: D::f is private
}
```

> **Standardese.** [over.match.general] defines a usable candidate as one that is selected by overload resolution and is accessible from the context of the use. Accessibility is checked on the winner; it does not remove inaccessible functions from the candidate set.

## Protected: access through your own type

`protected` is the one specifier with an extra rule. A member function or friend of `Derived` may use a protected non-static member of `Base`, but only through an object expression whose type is `Derived` or a class derived from `Derived`. It may not reach into an arbitrary `Base`, or into a sibling class that also derives from `Base`.

```cpp
struct Base { protected: int x = 0; };

struct Derived : Base {
  int ok(Derived& d) { return d.x; }   // OK: through Derived
  // int bad(Base& b) { return b.x; }  // ill-formed: through Base
  // auto p() { return &Base::x; }     // ill-formed: must name Derived
  auto q() { return &Derived::x; }     // OK, and its type is int Base::*
};
```

The reasoning is that protected members belong to the derived class's own share of the object. Without the rule, any class could derive from `Base` and then read the protected state of every other `Base` it was handed. The rule applies only to non-static members; a protected static member has no object to check and is accessible by name.

> **Standardese.** [class.protected] adds a check beyond the ordinary ones when a non-static member is protected in its naming class: the access must be through a pointer to, reference to, or object of the accessing class or a class derived from it, and forming a pointer to member must name that class.

## Friends

A friend declaration inside a class grants a function or class the same access the class's own members have. It can name a function, a member function of another class, a whole class, or a template.

```cpp
template<class T> class Box {
  T v{};
  template<class U> friend class Box;                     // every Box is a friend
  template<class U> friend U unwrap(const Box<U>&);       // every unwrap is a friend
public:
  template<class U> bool same(const Box<U>& o) const { return v == o.v; }
};
template<class U> U unwrap(const Box<U>& b) { return b.v; }
```

Friendship is granted, never inferred. It is **not inherited**: a class derived from a friend gets nothing. It is **not transitive**: a friend of a friend gets nothing. And it is **not reciprocal**: declaring `B` a friend of `A` gives `A` no access to `B`. What a friend does get is access through derived objects. A friend of `Base` may use `Base`'s private members when it names them through a `Derived` object, because the `Base` subobject is still accessed as a member of `Base`.

```cpp
class A { int secret = 1; friend class B; };
class B { public: int f(A& a) { return a.secret; } };  // OK
class C : public B {
  // int g(A& a) { return a.secret; }  // ill-formed: friendship is not inherited
};
```

### Hidden friends

A friend function that is first declared, and usually defined, inside the class is a member of the enclosing namespace, but ordinary lookup cannot find it. Only argument-dependent lookup finds it, when one of the arguments has the class as an associated class. This is the **hidden friend** idiom, and it is the preferred way to write operators and customization functions such as `swap`.

```cpp
namespace n {
struct V {
  int v;
  friend bool operator==(V a, V b) { return a.v == b.v; }
  friend void show(V) {}
};
}

void use(n::V a) {
  show(a);       // OK: found by ADL
  // n::show(a); // ill-formed: qualified lookup does not find a hidden friend
}
```

Hidden friends keep overload sets small. The operator is not a candidate for unrelated types, so it cannot be picked through an implicit conversion of some other argument, and diagnostics do not list it. [basic.lookup.argdep] is the rule that makes such a friend visible through its class.

## Access to bases and inherited names

A base class has an access too. With `public` inheritance, inherited members keep their access. With `protected`, public members become protected in the derived class. With `private`, they become private. A `class` inherits privately by default, a `struct` publicly. Base access also governs the conversion from `Derived*` to `Base*`: outside the class and its friends, converting to a private base is ill-formed, which is what makes private inheritance mean "implemented in terms of" rather than "is a".

A `using`-declaration can restore or change the access of an inherited member, provided the `using` itself can see it.

```cpp
struct B { protected: int x = 5; void f() {} };
struct D : B { using B::x; using B::f; };   // both now public in D
```

> **Pitfall.** A class name is also injected into its own scope as a member. If `B` inherits privately from `A`, then inside a class `C` derived from `B`, the plain name `A` finds the injected-class-name through `B`, which is private, and `A a;` is ill-formed. Writing `::A` finds the namespace-scope name and works.

## Templates, SFINAE and explicit instantiation

Access checking in templates uses the context of the template, as for any other code. Since C++11, access checking is also part of template argument substitution, as [temp.deduct.general] states. An expression that names an inaccessible member is a substitution failure, so detection idioms and concepts report "no such member" rather than producing a hard error.

```cpp
#include <type_traits>
#include <utility>

class P { void f(); public: void g(); };

template<class T, class = void> struct has_f : std::false_type {};
template<class T>
struct has_f<T, std::void_t<decltype(std::declval<T&>().f())>> : std::true_type {};

static_assert(!has_f<P>::value);                        // private f is "absent"
template<class T> concept HasF = requires(T t) { t.f(); };
static_assert(!HasF<P>);
```

There is one deliberate hole. [temp.spec.general] says the usual access checking rules do not apply to names in the declaration of an explicit instantiation or explicit specialization, outside function bodies and a few other places. Explicit instantiations have always had this exemption; C++20 extended it to explicit specializations and to the template arguments of partial specializations. That is why `template struct Thief<&Vault::gold>;` may name a private member in a template argument, a trick used by testing and serialization libraries.

## Nested and local classes

A nested class is a member of its enclosing class, so since C++11 it has the same access as any other member: it may use every private name of the enclosing class. The reverse does not hold. The enclosing class has no special access to the nested class's private members.

```cpp
class Outer {
  int x = 0;
  class Inner {
    int y = 0;
  public:
    int get(Outer& o) { return o.x; }   // OK: Inner is a member of Outer
  };
  // int peek(Inner& i) { return i.y; } // ill-formed: Outer is not Inner's friend
};
```

A local class, one defined inside a function body, may use the names that its enclosing function may use, as [class.access.general] states. Inside a member function, that includes the private members of the function's class. Friend declarations follow the same scoping: a friend declared in a nested class is a friend of that nested class only.

## What to remember

- Access is checked after lookup and overload resolution; a private best match is an error, not a reason to pick another function.
- Private members still hide outer names; qualify the outer name to reach it.
- Access is on names: `auto` can hold a private nested type, and virtual calls check the static type.
- Protected non-static members are reachable only through the accessing class or classes derived from it, including when forming `&Derived::m`.
- Friendship is not inherited, transitive or reciprocal.
- Hidden friends are found only by ADL, which keeps operators out of unrelated overload sets.
- Base access controls inherited member access and the derived-to-base conversion; `using` can change a member's access.
- Inaccessible members are substitution failures in SFINAE and concepts; explicit instantiations skip access checks.
- Nested classes see their enclosing class's private names, but not the other way round.

## Concept Map Outline

- **Access control and friends:** Access is a permission on names, checked after lookup and overload resolution.
  - **Checked last:** Lookup and overload resolution ignore access; the chosen name is then checked.
    - **Private best match:** A private overload that wins resolution makes the call ill-formed, not redirected.
    - **Private still hides:** A private base member hides a global of the same name; qualify with ::.
    - **Names, not types:** auto can hold a private nested type because the private name is never spelled.
    - **Virtual calls:** Access is checked on the static type's function; a private override still runs.
  - **Protected rule:** Protected non-static members are reachable only through the accessing class or its derived classes.
    - **Not through Base&:** Derived may not read a protected member through a plain Base reference.
    - **Pointer to member:** Must be formed as &Derived::m, which still has type T Base::*.
    - **Static members exempt:** The extra check applies only to non-static members.
  - **Friends:** A friend gets the same access as the granting class's own members.
    - **Kinds:** Functions, member functions, classes, and class or function templates can be friends.
    - **Not inherited:** A class derived from a friend gets no access.
    - **Not transitive:** A friend of a friend gets nothing, and friendship is not reciprocal.
    - **Hidden friends:** Defined in the class, found only by ADL, so they stay out of unrelated overload sets.
  - **Base access:** Inheritance access caps the access of inherited members and controls conversion to the base.
    - **Defaults:** class inherits privately and struct publicly; members default the same way.
    - **Derived-to-base:** Converting to a private base outside the class and its friends is ill-formed.
    - **using-declaration:** Can make an accessible inherited member public, protected or private in the derived class.
    - **Injected-class-name:** Inherited through a private base, the plain class name becomes inaccessible; use ::A.
  - **Templates:** Access checks interact with substitution and with explicit instantiation.
    - **SFINAE:** Since C++11 access is checked during substitution, so a private member reads as absent.
    - **Explicit instantiation:** Names in its declaration skip access checks, so a private member can be a template argument.
  - **Nested and local:** Classes inside classes and functions inherit the access of their surroundings.
    - **Nested class:** A member of the enclosing class, so it may use all its private names (C++11).
    - **One-way only:** The enclosing class has no special access to the nested class's private members.
    - **Local class:** May use the names its enclosing function may use, including that class's private members.

## Standardese Quiz Questions

### Question 1 [warmup] ([over.match.general], [class.access.general])

Is the definition of `g` well-formed?

```cpp
struct S {
  void f(int);
private:
  void f(double);
};

void g(S& s) { s.f(1.0); }
```

A. Well-formed: `f(double)` is private, so `f(int)` is called after converting `1.0`
B. Ill-formed: overload resolution selects the private `f(double)`
C. Ill-formed: the call is ambiguous between the two overloads
D. Undefined behavior: a private member function is called from outside the class

**Answer (B):** Ill-formed: overload resolution selects the private `f(double)`

**Why:** Access is checked after overload resolution. `f(double)` is an exact match and wins; then the compiler finds it is private in this context and the program is ill-formed. Access never removes a candidate, so the first option, which is what many people expect, describes a rule C++ does not have. There is no ambiguity because the exact match beats the floating-integral conversion.

### Question 2 [warmup] ([class.friend])

Which member function is ill-formed?

```cpp
class A { int secret = 1; friend class B; };

class B {
public:
  int f(A& a) { return a.secret; }
};

class C : public B {
public:
  int g(A& a) { return a.secret; }
};
```

A. Neither: `C` inherits `B`'s friendship
B. Only `B::f`, because a friend class must be declared before `A`
C. Both, because `secret` is private
D. Only `C::g`

**Answer (D):** Only `C::g`

**Why:** Friendship is not inherited: `A` granted access to `B`, and a class derived from `B` gets none of it, so `C::g` is ill-formed. `B::f` is fine because `B`'s member functions have the same access as `A`'s own members, and a friend declaration may name a class that is declared later. The tempting first option treats friendship like a member that a derived class inherits, which it is not.

### Question 3 [warmup] ([class.access.virt], [class.virtual])

What does this program print?

```cpp
#include <cstdio>

struct B { virtual void f() { std::puts("B"); } };
class D : public B { void f() override { std::puts("D"); } };

int main() {
  D d;
  B& b = d;
  b.f();
}
```

A. `B`, because `D::f` is private and cannot be called
B. `D`
C. Nothing: the program is ill-formed because an override may not be less accessible
D. Undefined behavior

**Answer (B):** `D`

**Why:** Access for a virtual call is checked on the name in the call expression, using the static type: `b.f()` names `B::f`, which is public. The call then dispatches to the final overrider, `D::f`, and prints `D`. An override may have any access; only `d.f()` would be ill-formed. Access never changes which function a virtual call reaches.

### Question 4 [tricky] ([class.protected])

Which member function of `Derived` is ill-formed?

```cpp
struct Base { protected: int x = 0; };

struct Derived : Base {
  int a()            { return x; }
  int b(Derived& d)  { return d.x; }
  int c(Base& o)     { return o.x; }
};
```

A. Only `c`
B. Only `b`, because `d` might be a different object
C. `b` and `c`, since both access another object's protected member
D. None of them

**Answer (A):** Only `c`

**Why:** A protected non-static member of `Base` may be used in `Derived` only through an object expression of type `Derived` or a class derived from it. `a` uses `this->x` and `b` uses a `Derived&`, so both are fine, even though `d` is another object. `c` goes through a plain `Base&`, which might be a sibling class's object, so the extra protected check makes it ill-formed.

### Question 5 [tricky] ([class.pre], [class.access.base], [class.member.lookup])

Is the definition of `C::f` well-formed?

```cpp
struct A {};
struct B : private A {};

struct C : B {
  void f() { A a; (void)a; }
};
```

A. Well-formed: `A` is a public namespace-scope struct
B. Ill-formed: a class cannot use a type that its base inherits privately
C. Ill-formed: `A` finds the injected-class-name inherited through `B`, which is private
D. Well-formed, but `a` has type `B::A`, a distinct type

**Answer (C):** Ill-formed: `A` finds the injected-class-name inherited through `B`, which is private

**Why:** Every class has its own name injected into its scope as a member. Unqualified lookup inside `C` searches `C`'s bases before the namespace, so `A` finds `A`'s injected-class-name as a member of `B`, where it is private because `B` inherits `A` privately. Writing `::A a;` finds the namespace-scope name and is well-formed, which shows the second option is wrong: the type itself is usable, only that spelling is not.

### Question 6 [tricky] ([class.friend], [basic.lookup.argdep])

Which calls in `main` are well-formed?

```cpp
namespace n {
struct V {
  int v;
  friend void show(V) {}
};
}

int main() {
  n::V a{1};
  show(a);     // #1
  n::show(a);  // #2
}
```

A. Only #1
B. Both: `show` is a member of namespace `n`
C. Only #2
D. Neither: a friend defined in a class is a member function of that class

**Answer (A):** Only #1

**Why:** A friend function first declared in a class is a member of the enclosing namespace, but it is not visible to ordinary or qualified lookup; only argument-dependent lookup finds it, through the associated class `V`. So #1 works and #2 is ill-formed. The second option is half right: `show` really does belong to `n`, it just cannot be named that way until it is also declared at namespace scope.

### Question 7 [standardese] ([temp.spec.general], [temp.explicit], [class.friend])

In C++23, what does this program do?

```cpp
#include <cstdio>

class Vault { int gold = 7; };

template<int Vault::* P>
struct Thief { friend int Vault::* steal() { return P; } };

int Vault::* steal();
template struct Thief<&Vault::gold>;

int main() { Vault v; std::printf("%d\n", v.*steal()); }
```

A. Ill-formed: `&Vault::gold` names a private member
B. Undefined behavior: private members may not be read from outside
C. Ill-formed: a friend function cannot be defined in a class template
D. It prints `7`

**Answer (D):** It prints `7`

**Why:** The usual access checking rules do not apply to names in the declaration of an explicit instantiation, so `&Vault::gold` is allowed as a template argument there. Instantiating `Thief` defines the friend `steal`, which returns that pointer to member, and `v.*steal()` reads `gold`. The first option would be right for an ordinary use such as `Thief<&Vault::gold> t;`. Access is a compile-time rule about names, so nothing here is undefined.

### Question 8 [standardese] ([class.access.nest], [class.access.general])

Which member function is ill-formed?

```cpp
class Outer {
  int x = 0;
  class Inner {
    int y = 0;
  public:
    int get(Outer& o) { return o.x; }
  };
public:
  int peek(Inner& i) { return i.y; }
};
```

A. Only `Inner::get`: a nested class has no special access to its enclosing class
B. Only `Outer::peek`
C. Both
D. Neither: enclosing and nested classes are implicitly friends of each other

**Answer (B):** Only `Outer::peek`

**Why:** A nested class is a member of its enclosing class and, since C++11 (CWG 45), has the same access as any other member, so `Inner::get` may read `Outer::x`. The relationship is one-way: [class.access.nest] gives the enclosing class no special access to the nested class's members, so `peek` cannot read `Inner::y` and is ill-formed. The first option describes the C++98 wording, which compilers no longer follow.

# Conversion functions and explicit

> A class can convert from other types through converting constructors and to other types through conversion functions. The language applies at most one of these implicitly, and `explicit` removes a conversion from the implicit contexts without removing it from direct initialization.

- **Source:** C++ Atlas (https://cppatlas.com/topics/conversion-functions-and-explicit)
- **Track:** Classes
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [class.conv] (https://eel.is/c++draft/class.conv), [class.conv.general] (https://eel.is/c++draft/class.conv.general), [class.conv.ctor] (https://eel.is/c++draft/class.conv.ctor), [class.conv.fct] (https://eel.is/c++draft/class.conv.fct), [dcl.fct.spec] (https://eel.is/c++draft/dcl.fct.spec), [conv.general] (https://eel.is/c++draft/conv.general), [over.match.copy] (https://eel.is/c++draft/over.match.copy), [over.match.conv] (https://eel.is/c++draft/over.match.conv), [over.match.ctor] (https://eel.is/c++draft/over.match.ctor), [over.match.list] (https://eel.is/c++draft/over.match.list), [over.best.ics] (https://eel.is/c++draft/over.best.ics), [temp.deduct.conv] (https://eel.is/c++draft/temp.deduct.conv)
- **cppreference links:** [Converting constructor](https://en.cppreference.com/w/cpp/language/converting_constructor), [User-defined conversion function](https://en.cppreference.com/w/cpp/language/cast_operator), [explicit specifier](https://en.cppreference.com/w/cpp/language/explicit), [Copy-initialization](https://en.cppreference.com/w/cpp/language/copy_initialization), [Implicit conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion)
- **Prerequisites:** implicit-conversions, initialization-forms, overload-resolution

## The one idea

A user-defined conversion is a function call the compiler inserts for you. There are two ways to write one. A **converting constructor** of `T` turns some other type into a `T`. A **conversion function** `operator U()` of `T` turns a `T` into a `U`. Either way, the compiler may insert at most one such call into an implicit conversion, surrounded by ordinary standard conversions.

`explicit` does not delete a conversion. It moves it out of the contexts where the compiler inserts conversions silently, mainly copy-initialization, and leaves it available where you asked for a `T` by name: direct-initialization, casts, and for `operator bool`, the conditions of `if` and loops.

> **Mental model.** An implicit conversion sequence is standard conversions, then at most one user-defined call, then standard conversions. `explicit` means "only when I write the target type myself".

## Converting constructors and conversion functions

Any constructor that is not `explicit` is a converting constructor, including ones with several parameters, which convert from braced lists. A conversion function is a member named `operator` followed by a type. It has no parameters and no declared return type, can be `const`, `virtual`, or a template, and since C++14 may be `operator auto()` with a deduced type.

Some conversion functions are never used implicitly. [class.conv.fct] says a conversion function is never used to convert an object to its own type, to a base class, or to `void`. Converting to a base is handled by the derived-to-base conversion, so the function would be dead code; GCC and Clang both warn with `-Wclass-conversion`.

Conversion functions are inherited like other members and may be virtual, so a call through a base reference can convert using the derived class's override. A conversion function in a derived class hides one in a base only when both convert to the same type; `operator long()` in the derived class leaves the base's `operator int()` visible.

`explicit` matters for constructors with several parameters too, because braced lists use them. With `explicit S(int, int)`, both `S s = {1, 2};` and `return {1, 2};` are ill-formed, while `S s{1, 2};` is fine.

```cpp
#include <cstdio>
struct B {};
struct D : B { operator B() const { std::puts("conv"); return {}; } };

void slice(D d) {
  B b = d;   // copies the B subobject; the conversion function is not called
  (void)b;
}
```

## The one-user-defined-conversion limit

[class.conv.general] says at most one user-defined conversion is implicitly applied to a single value. Standard conversions on either side do not count, so `int` to a class taking `double`, or a class with `operator long()` to `short`, are fine. Two class hops are not.

```cpp
#include <string>
struct Name { Name(std::string) {} };
void greet(Name);

void use() {
  // greet("bob");                // ill-formed: const char* -> std::string -> Name is two
  greet(std::string("bob"));      // OK: one user-defined conversion
  greet(Name("bob"));             // OK: the parameter of Name(std::string) gets the one hop
}
```

The limit is per value, not per expression. In `Name("bob")` the compiler is initializing the parameter of `Name`'s constructor, and that initialization may use its own conversion. The same is why `B b(1);` works when `B` has a constructor from `A` and `A` has a constructor from `int`, while `B b = 1;` does not: direct-initialization calls a `B` constructor whose parameter is converted from `1` in one hop, whereas copy-initialization needs one implicit conversion from `int` all the way to `B`.

The limit also shapes overload resolution. Two user-defined conversion sequences can be ranked against each other only when they use the same constructor or conversion function. If `f(A)` and `f(B)` both exist and `A` and `B` both have a constructor from `int`, then `f(1)` is ambiguous: each candidate needs a different user-defined conversion, and neither is better.

## Copy-initialization and direct-initialization pick from different sets

The two forms of initialization build different candidate sets, and most surprises come from that.

For `T t = u;` with `u` of another type, [over.match.copy] takes the converting constructors of `T` and the non-explicit conversion functions of `u`'s type that yield `T` or a derived class. Explicit constructors are not candidates at all, so a worse non-explicit one can win.

For `T t(u);`, [over.match.ctor] takes all constructors of `T`, explicit or not. The argument may then use a conversion function of `u` to reach a constructor's parameter type.

```cpp
#include <cstdio>
struct S {
  explicit S(int) { std::puts("int"); }
  S(double)       { std::puts("double"); }
};

int main() {
  S a = 1;   // prints double: S(int) is not a candidate
  S b(1);    // prints int
}
```

Copy-list-initialization is different again. For `S s = {1};`, [over.match.list] considers all constructors, explicit included, and if an explicit one wins, the program is ill-formed. It does not fall back to `S(double)`.

When the target is not a class, [over.match.conv] applies. Copy-initialization considers the non-explicit conversion functions that yield the target or something a standard conversion turns into it. Direct-initialization adds the explicit ones, but only those whose result reaches the target through at most a qualification conversion. An `explicit operator int()` therefore makes `int i(e);` well-formed and `long l(e);` ill-formed.

> **Standardese.** [over.match.conv] adds explicit conversion functions to the candidates only for direct-initialization, and only those yielding the target type or a type convertible to it by a qualification conversion. A promotion or integral conversion after an explicit conversion function is not allowed.

## Constructor versus conversion function

When both `A(const B&)` and `B::operator A() const` exist, copy-initializing an `A` from a `B` puts both in one candidate set. Both bind the `B` to a `const B&`, one as the constructor's parameter and one as the implicit object parameter, so neither is better and the conversion is ambiguous.

```cpp
struct B;
struct A { A() = default; A(const B&); };
struct B { operator A() const; };

// A a = B{};   // ill-formed: ambiguous between A(const B&) and B::operator A
```

Clang rejects this. GCC 16 accepts it by default as an extension and calls the constructor, and diagnoses the ambiguity under `-pedantic-errors`. Do not rely on the extension. Direct-initialization `A a(B{});` is not ambiguous, because only constructors of `A` are candidates, and `A(const B&)` beats `A(A&&)`, which would need the conversion function as a user-defined conversion. Small changes tip the balance: if `operator A()` is not `const`, it wins copy-initialization outright, because binding the non-const implicit object parameter is better than binding `const B&`.

> **Pitfall.** Providing a conversion in both directions, or in both classes, is almost always a mistake. Pick one owner for each conversion.

## explicit, explicit(bool), and contextual conversion to bool

Before C++11, a class that wanted to be testable in `if (p)` had to convert to something, and `operator bool()` let it be added to integers, compared with unrelated classes, and passed to `int` parameters. The safe-bool idiom worked around this by converting to a pointer to member, which could be tested but not used in arithmetic. C++11 replaced it with `explicit operator bool`.

An explicit conversion to `bool` is used only where the language **contextually converts to bool**: the conditions of `if`, `while`, `for` and `do`, the operands of `!`, `&&` and `||`, the first operand of `?:`, `static_assert`, and `noexcept(expr)`. It is also used by direct-initialization of a `bool`. It is not used for `bool b = f;`, for `return f;` in a function returning `bool`, or for `f == true`.

```cpp
struct F { explicit operator bool() const { return true; } };

bool test(F f) {
  if (f) {}             // OK: contextual
  bool a = !f;          // OK: contextual
  bool b(f);            // OK: direct-initialization
  // bool c = f;        // ill-formed: copy-initialization
  // int  i(f);         // ill-formed: bool -> int is not a qualification conversion
  return a || b;        // OK; plain "return f;" would be ill-formed
}
```

C++20 added `explicit(bool)`, whose operand is a constant expression of type `bool`, typically one that depends on template parameters. It lets one constructor template be implicit exactly when the underlying conversion is, which is how `std::pair` and `std::optional` became conditionally explicit without duplicated overloads.

```cpp
#include <string>
#include <type_traits>

template<class T> struct Wrap {
  T v;
  template<class U>
  explicit(!std::is_convertible_v<U, T>) Wrap(U&& u) : v(static_cast<U&&>(u)) {}
};

Wrap<std::string> a = "hi";                     // OK: const char* converts implicitly
Wrap<std::string> b(std::string_view("hi"));    // OK: direct-initialization
// Wrap<std::string> c = std::string_view("hi"); // ill-formed: explicit here
```

Mark single-argument constructors and conversion functions `explicit` by default. The exceptions are types meant to be interchangeable with their source, like `std::string` from `const char*`.

## Conversion function templates

A conversion function may be a template. Its template arguments are deduced from the type the conversion is needed for, not from any argument. [temp.deduct.conv] strips references and top-level cv-qualifiers from that required type before deducing, so converting to `const int&` deduces `int`.

```cpp
struct Any {
  template<class T> operator T() const { return T{}; }
};

int i = Any{};          // T = int
const int& r = Any{};   // T = int, and r binds to a temporary
double d = Any{};       // T = double
```

Such a type converts to everything, which makes it useful for test doubles and for proxy objects, and dangerous in overload sets, where it makes every overload viable. Constrain the template, for example with a concept, to keep it from matching by accident.

## What to remember

- An implicit conversion contains at most one user-defined conversion, with standard conversions allowed before and after.
- A conversion function to the class itself, a base, or `void` is never used implicitly.
- Copy-initialization excludes explicit constructors from the candidates; copy-list-initialization includes them and is ill-formed if one wins.
- Direct-initialization considers explicit constructors, and explicit conversion functions followed by at most a qualification conversion.
- `explicit operator bool` works in conditions, `!`, `&&`, `||`, `?:` and `static_assert`, but not in `return`, `==` or `bool b = f;`.
- A converting constructor and a matching `const` conversion function make copy-initialization ambiguous; GCC accepts it only as an extension.
- `explicit(bool)` (C++20) makes a constructor conditionally explicit.
- Conversion function templates deduce from the target type with references and top-level cv removed.

## Concept Map Outline

- **Conversion functions and explicit:** User-defined conversions in both directions, at most one per implicit conversion.
  - **Two directions:** A constructor converts into the class; operator U() converts out of it.
    - **Converting constructor:** Any non-explicit constructor, including multi-parameter ones used by braced lists.
    - **Conversion function:** No parameters, no declared return type; may be const, virtual, a template or operator auto.
    - **Never used implicitly:** Conversion to the class itself, a base class, or void is never applied implicitly.
  - **One-conversion limit:** At most one user-defined conversion is applied implicitly to a single value.
    - **Standard conversions around:** Promotions or conversions may come before and after the one user-defined call.
    - **Two hops fail:** const char* to std::string to Name is two user-defined conversions, so it fails.
    - **Per value:** Direct-initialization converts a constructor's argument separately, so B b(1) can work where B b = 1 fails.
  - **Candidate sets:** The form of initialization decides which functions are even considered.
    - **Copy-initialization:** Converting constructors plus non-explicit conversion functions; explicit ones are not candidates.
    - **Direct-initialization:** All constructors, plus explicit conversion functions followed by at most a qualification conversion.
    - **Copy-list-initialization:** Explicit constructors are candidates, and choosing one makes it ill-formed.
    - **Ctor versus conv function:** A(const B&) and B::operator A() const make A a = B{} ambiguous.
  - **explicit operator bool:** C++11 replacement for the safe-bool idiom.
    - **Contextual contexts:** if, while, for, do, !, &&, ||, the first operand of ?:, static_assert and noexcept(expr).
    - **Not contextual:** bool b = f, return f, f == true and int i(f) are all ill-formed.
    - **Safe-bool history:** Before C++11, classes converted to a member pointer so they were testable but not arithmetic.
  - **explicit(bool):** C++20: a constant bool decides whether the constructor is explicit.
    - **Conditionally explicit:** explicit(!is_convertible_v<U, T>) makes a wrapper exactly as implicit as T.
    - **Library use:** std::pair and std::optional constructors are conditionally explicit this way.
  - **Conversion templates:** template<class T> operator T() deduces T from the required target type.
    - **Deduction rule:** References and top-level cv are stripped, so const int& deduces int.
    - **Converts to anything:** Makes every overload viable; constrain it to avoid accidental matches.

## Standardese Quiz Questions

### Question 1 [warmup] ([over.match.copy], [over.match.ctor], [class.conv.ctor])

What does this program print?

```cpp
#include <cstdio>

struct S {
  explicit S(int) { std::puts("int"); }
  S(double)       { std::puts("double"); }
};

int main() {
  S a = 1;
  S b(1);
  (void)a; (void)b;
}
```

A. `int` then `int`
B. Nothing: `S a = 1;` is ill-formed because the best constructor is explicit
C. `double` then `int`
D. `double` then `double`

**Answer (C):** `double` then `int`

**Why:** In copy-initialization from a non-class type, only converting constructors are candidates, and an explicit constructor is not a converting constructor. So `S a = 1;` calls `S(double)` after converting `1`, and direct-initialization `S b(1);` considers every constructor and picks the exact match `S(int)`. The second option describes copy-list-initialization, `S a = {1};`, which does consider explicit constructors and is ill-formed if one wins.

### Question 2 [warmup] ([class.conv.general], [over.best.ics])

Is the call in `main` well-formed?

```cpp
#include <string>

struct Name { Name(std::string) {} };
void greet(Name) {}

int main() { greet("bob"); }
```

A. Ill-formed: it needs two user-defined conversions
B. Well-formed: `const char*` converts to `std::string`, which converts to `Name`
C. Well-formed, because the first conversion is a standard library one
D. Ill-formed: string literals cannot initialize class parameters

**Answer (A):** Ill-formed: it needs two user-defined conversions

**Why:** An implicit conversion sequence may contain at most one user-defined conversion. Turning `const char*` into `std::string` is one, through a constructor, and turning `std::string` into `Name` is a second, so no viable conversion exists. Library types get no special treatment, which rules out the third option. `greet(std::string("bob"))` or `greet(Name("bob"))` each need only one implicit hop and are fine.

### Question 3 [warmup] ([class.conv.fct], [conv.general], [over.match.conv])

Given `struct F { explicit operator bool() const; };` and `F f;`, which of these is ill-formed?

A. `if (f) {}`
B. `bool a = !f;`
C. `bool b(f);`
D. `bool c = f;`

**Answer (D):** `bool c = f;`

**Why:** An explicit conversion function is used only by direct-initialization and by contexts that contextually convert to `bool`. The `if` condition and the operand of `!` are contextual conversions, and `bool b(f);` is direct-initialization, so all three work. `bool c = f;` is copy-initialization, which does not consider explicit conversion functions; `return f;` from a function returning `bool` fails for the same reason.

### Question 4 [tricky] ([over.match.list], [dcl.init.list])

Is this declaration well-formed?

```cpp
struct S {
  explicit S(int) {}
  S(double) {}
};

S s = {1};
```

A. Well-formed: it calls `S(double)`, as `S s = 1;` would
B. Ill-formed: `S(int)` is selected and it is explicit
C. Ill-formed: narrowing from `int` to `double` in a braced list
D. Well-formed: it calls `S(int)`, because braces allow explicit constructors

**Answer (B):** Ill-formed: `S(int)` is selected and it is explicit

**Why:** Copy-list-initialization considers all constructors, including explicit ones, and [over.match.list] says that if an explicit constructor is chosen, the initialization is ill-formed. `S(int)` is the exact match, so it wins and then fails. This differs from `S s = 1;`, where explicit constructors are not candidates and `S(double)` is called. There is no narrowing issue because `S(double)` is not selected, and `1` to `double` would not narrow anyway, since the constant fits exactly.

### Question 5 [tricky] ([over.match.copy], [over.ics.rank], [over.match.best])

Under the C++23 standard, is the declaration of `a` well-formed?

```cpp
struct B;
struct A { A() = default; A(const B&); };
struct B { operator A() const; };

A a = B{};
```

A. Well-formed: constructors are always preferred over conversion functions
B. Well-formed: guaranteed elision makes the conversion function the better match
C. Implementation-defined
D. Ill-formed: the conversion is ambiguous

**Answer (D):** Ill-formed: the conversion is ambiguous

**Why:** Copy-initialization of `A` from a `B` makes both `A(const B&)` and `B::operator A() const` candidates. Each binds the `B` prvalue to a `const B&`, one as the constructor parameter and one as the implicit object parameter, so the conversion sequences are indistinguishable and no tie-breaker applies. Clang reports the ambiguity; GCC 16 accepts it by default as an extension and calls the constructor, which is where the first option comes from, but rejects it with `-pedantic-errors`.

### Question 6 [tricky] ([class.conv.fct], [dcl.init.general])

What does this program print?

```cpp
#include <cstdio>

struct B {};
struct D : B {
  operator B() const { std::puts("conv"); return {}; }
};

int main() {
  D d;
  B b = d;
  (void)b;
  std::puts("done");
}
```

A. `conv` then `done`
B. `done`
C. Nothing: the program is ill-formed because the conversion is ambiguous
D. Either output; it is unspecified which conversion is used

**Answer (B):** `done`

**Why:** A conversion function is never used to convert an object to its own type or to a base class; that job belongs to the derived-to-base conversion. So `B b = d;` binds `B`'s copy constructor to the `B` subobject of `d` and the conversion function is not a candidate. Calling `d.operator B()` explicitly would still work, which is why the declaration is legal, and compilers warn with `-Wclass-conversion`.

### Question 7 [standardese] ([over.match.conv], [expr.static.cast], [dcl.init.general])

Which declaration in `use` is ill-formed?

```cpp
struct E { explicit operator int() const { return 4; } };

void use(E e) {
  int a(e);                   // #1
  int b = static_cast<int>(e); // #2
  long c(e);                  // #3
}
```

A. #1 only: explicit conversion functions need a cast
B. #3 only
C. #1 and #3
D. None of them

**Answer (B):** #3 only

**Why:** For direct-initialization of a non-class type, [over.match.conv] adds explicit conversion functions to the candidates, but only those whose result reaches the target type by at most a qualification conversion. #1 and #2 (a static_cast is defined as a direct-initialization) target `int` exactly. #3 would need an integral conversion from `int` to `long` after the explicit function, which is not allowed, so there is no viable conversion. The same rule makes `int i(f);` ill-formed for an `explicit operator bool`.

### Question 8 [standardese] ([temp.deduct.conv], [over.match.ref], [dcl.init.ref])

For the initialization of `r`, what is `T` deduced as?

```cpp
struct Any {
  template<class T> operator T() const { return T{}; }
};

const int& r = Any{};
```

A. `const int&`
B. `const int`
C. `int`
D. Deduction fails, so the program is ill-formed

**Answer (C):** `int`

**Why:** A conversion function template deduces `T` from the type required as the result of the conversion. [temp.deduct.conv] uses the referred-to type when that type is a reference, and then ignores its top-level cv-qualifiers, so `const int&` becomes `const int` and then `int`. The conversion returns an `int` prvalue, which is materialized as a temporary and bound to `r`, with its lifetime extended.

# Pointers to members

> A pointer to member names a member of a class without naming an object, and is applied to an object later with `.*` or `->*`. It converts along the inheritance hierarchy in the opposite direction from object pointers, and `std::invoke` turns it into an ordinary callable.

- **Source:** C++ Atlas (https://cppatlas.com/topics/pointers-to-members)
- **Track:** Classes
- **Estimated reading time:** 11 minutes
- **ISO C++ clauses:** [dcl.mptr] (https://eel.is/c++draft/dcl.mptr), [expr.unary.op] (https://eel.is/c++draft/expr.unary.op), [expr.mptr.oper] (https://eel.is/c++draft/expr.mptr.oper), [conv.mem] (https://eel.is/c++draft/conv.mem), [expr.static.cast] (https://eel.is/c++draft/expr.static.cast), [over.over] (https://eel.is/c++draft/over.over), [basic.compound] (https://eel.is/c++draft/basic.compound), [func.invoke] (https://eel.is/c++draft/func.invoke), [func.require] (https://eel.is/c++draft/func.require), [func.memfn] (https://eel.is/c++draft/func.memfn), [namespace.std] (https://eel.is/c++draft/namespace.std)
- **cppreference links:** [Pointer declaration (pointers to members)](https://en.cppreference.com/w/cpp/language/pointer), [Member access operators](https://en.cppreference.com/w/cpp/language/operator_member_access), [Address of an overloaded function](https://en.cppreference.com/w/cpp/language/overloaded_address), [std::invoke](https://en.cppreference.com/w/cpp/utility/functional/invoke), [std::mem_fn](https://en.cppreference.com/w/cpp/utility/functional/mem_fn)
- **Prerequisites:** member-functions-and-this, inheritance-and-virtual-functions

## The one idea

A pointer to member is a **path into an object**, not an address. `&S::m` means "the member `m` of whatever `S` you give me later". It does not point at memory, it cannot be converted to `void*`, and it becomes a real lvalue only when you combine it with an object using `.*` or `->*`.

Because it describes where a member sits inside a class, its conversions run the opposite way from object pointers. An `S*` converts to a pointer to its base. An `int Base::*` converts to `int Derived::*`, since every member of the base is also a member of the derived class.

> **Mental model.** An object pointer answers "which object?". A pointer to member answers "which part?", and needs an object before it means anything.

## Forming and applying them

The type is spelled with the class in front of the star: `int S::*` is a pointer to an `int` data member of `S`, and `int (S::*)(int) const` is a pointer to a `const` member function taking an `int`. It is formed only by `&` applied to a qualified name. Inside a member function, writing `&(S::m)` with parentheses, or plain `&m`, produces an ordinary `int*` to the member of `*this`.

```cpp
#include <cstdio>

struct S {
  int a = 1, b = 2;
  int twice(int x) const { return 2 * x; }
};

int main() {
  int S::* pm = &S::b;
  int (S::*pf)(int) const = &S::twice;
  S s;
  S* p = &s;
  std::printf("%d %d\n", s.*pm, (p->*pf)(pm == &S::b));   // 2 2
  pm = nullptr;                                         // null member pointer
}
```

The parentheses around `(p->*pf)` are required. `.*` and `->*` bind more loosely than a function call, so `s.*pf(1)` parses as `s.*(pf(1))` and is ill-formed.

The result of `.*` on a data member has the value category of the object: an lvalue object gives an lvalue, an rvalue object gives an xvalue. `->*` on a data member always gives an lvalue. For member functions, the ref-qualifiers apply: a `&&`-qualified function can only be called through an rvalue object. Applying a null pointer to member is undefined behavior.

Member pointers are values like any other. They can be compared with `==` and `!=`, where a null member pointer compares unequal to every pointer to an actual member, but `<` and the other relational operators do not apply to them. They can also be non-type template arguments, and they can sit in `constexpr` tables, which is how reflection-free serializers map field names to fields.

```cpp
#include <cstdio>
#include <utility>

struct Config { int port; int threads; };

constexpr std::pair<const char*, int Config::*> fields[] = {
  {"port", &Config::port}, {"threads", &Config::threads}};

template<int Config::* M> int get(const Config& c) { return c.*M; }

void dump(const Config& c) {
  for (auto [name, m] : fields) std::printf("%s=%d\n", name, c.*m);
  std::printf("%d\n", get<&Config::threads>(c));
}
```

Static members are not reached through pointers to members. `&S::static_member` is an ordinary object or function pointer. Members of reference type and bit-fields cannot be pointed to at all. A C++23 explicit object member function behaves like a static one here: `&S::f` for `int f(this const S&)` has the type `int (*)(const S&)`, a topic covered in crtp-and-deducing-this.

## Conversions run the other way

[conv.mem] allows an implicit conversion from `T Base::*` to `T Derived::*`. Whatever `Base` member the pointer names, a `Derived` object contains it. The reverse direction needs `static_cast`, because the pointer might name a member that only some derived classes have.

```cpp
struct B { int x = 1; };
struct D : B { int y = 2; };

int D::* pd = &B::x;                          // OK: implicit, Base -> Derived
// int B::* bad = &D::y;                      // ill-formed: no implicit Derived -> Base
int B::* pb = static_cast<int B::*>(&D::y);   // OK, but only use it on a D

int read(B& b) { return b.*pb; }              // defined only if b is really a D
```

The rules have sharp edges that object pointers do not.

- The implicit conversion is ill-formed if `Base` is inaccessible, ambiguous, or a **virtual** base of `Derived`. A virtual base sits at a different offset in every most-derived class, so no fixed adjustment exists.
- `&D::x`, where `x` is declared in `B`, has type `int B::*`, not `int D::*`. The type records the class that declares the member, not the class you named.
- Using a pointer whose member is absent from the object's dynamic type is undefined behavior. [expr.mptr.oper] says so directly.

```cpp
#include <type_traits>
struct B { int x; void f(); };
struct D : B {};
static_assert(std::is_same_v<decltype(&D::x), int B::*>);
static_assert(std::is_same_v<decltype(&D::f), void (B::*)()>);
```

> **Pitfall.** Because `&D::f` has type `void (B::*)()`, template argument deduction sees `B`, not `D`. A template that deduces the class from a member pointer, such as `template<class C> void bind(void (C::*)())`, deduces `C = B` for `&D::f`.

## Virtual functions through member pointers

A pointer to a virtual member function keeps the virtual behaviour. Calling it through an object dispatches to the final overrider of the dynamic type, exactly like a call by name. There is no member pointer equivalent of the qualified call `b.B::f()`, which suppresses dispatch.

```cpp
#include <cstdio>
struct B { virtual void f() { std::puts("B::f"); } };
struct D : B { void f() override { std::puts("D::f"); } };

int main() {
  void (B::*pf)() = &B::f;
  D d;
  B* bp = &d;
  (bp->*pf)();   // D::f
  bp->B::f();    // B::f: only a qualified name turns dispatch off
}
```

## What they look like in memory

Nothing in this section is guaranteed by the standard. The sizes and encodings below are implementation practice, and code must not depend on them.

Under the Itanium C++ ABI, used by GCC and Clang on Linux and macOS, a pointer to data member is a single `ptrdiff_t` holding the byte offset of the member, and the null value is `-1`, because offset 0 is a valid member. A pointer to member function is two words: a function address or a virtual table offset, plus an adjustment added to `this`. That adjustment is what makes conversions across multiple inheritance work.

```text
Itanium ABI, 64-bit
  int S::*            [ offset (ptrdiff_t) ]          null = -1
  void (S::*)()       [ ptr | adj ]                   two words, 16 bytes
    x86-64:   virtual if ptr is odd, ptr = 1 + vtable offset
    AArch64:  virtual if adj is odd, ptr = vtable offset
```

On arm64 macOS, a pointer to the first virtual function measured as `ptr = 0, adj = 1` with both compilers, and a data member at offset 8 stored the value 8. MSVC is different again: the size of its member function pointers depends on the inheritance model, from a single code pointer for single inheritance to several fields for virtual inheritance or for a class that is still incomplete where the pointer type is used.

> **Standardese.** [basic.compound] lists pointers to members as their own compound type, separate from object and function pointers. [conv.mem] gives null member pointer values and the base-to-derived conversion; there is no conversion to or from `void*` or integers, and a `reinterpret_cast` between two member pointer types has an unspecified result except that casting back recovers the original.

## std::invoke, std::mem_fn and projections

Calling through a member pointer needs different syntax for an object, a pointer, a smart pointer, and a `std::reference_wrapper`. `std::invoke` hides all four behind one call, as specified by the INVOKE rules in [func.require] that [func.invoke] refers to. For a data member it returns a reference whose value category follows the object, so `std::invoke(&P::age, p) = 41;` assigns.

```cpp
#include <functional>
#include <memory>

struct P { int age; int older(int n) const { return age + n; } };

void demo(P& p, std::unique_ptr<P>& up) {
  std::invoke(&P::age, p) = 41;          // object: int&
  int a = std::invoke(&P::older, up, 1); // smart pointer: dereferenced with *
  int b = std::invoke(&P::age, &p);      // raw pointer
  auto m = std::mem_fn(&P::older);       // a function object wrapping INVOKE
  int c = m(std::ref(p), 2);             // reference_wrapper is unwrapped
  (void)a; (void)b; (void)c;
}
```

`std::mem_fn` packages the same behaviour as a reusable function object, which predates lambdas and is still handy as an argument. To pass a member function as a callback, C++20's `std::bind_front(&Widget::on_click, this)` binds the object as the first INVOKE argument. It stores `this` as a plain pointer, so the widget must outlive the callable; the member pointer does nothing to keep the object alive. For a single call site, a lambda that captures the object is usually clearer and lets the compiler see the target directly. The most common modern use is a **projection**. Ranges algorithms accept a projection that they apply through `std::invoke` before comparing, so a member pointer is enough to sort or search by a field.

```cpp
#include <algorithm>
#include <string>
#include <vector>

struct Person { std::string name; int age; };

void by_age(std::vector<Person>& v) {
  std::ranges::sort(v, {}, &Person::age);                   // compare ages
  auto it = std::ranges::find(v, 25, &Person::age);         // find age 25
  (void)it;
}
```

## Taking the address of an overloaded member

`&S::f` names an overload set if `f` is overloaded, and an overload set has no type. [over.over] resolves it from the target: the type of the variable being initialized, a parameter, or a cast. With `auto` or a deduced template parameter there is no target, and the expression is ill-formed.

```cpp
struct S {
  void f(int);
  void f(double);
};

void (S::*p)(int) = &S::f;                         // picks f(int)
auto q = static_cast<void (S::*)(double)>(&S::f);  // picks f(double)
// auto r = &S::f;                                 // ill-formed: no target type
```

Standard library members are a special case. [namespace.std] says forming a pointer to a non-static member function of a standard library class, such as `&std::string::size`, has unspecified behavior and may be ill-formed. Implementations are allowed to add overloads, default arguments, or extra template parameters to those members. Wrap the call in a lambda instead.

## What to remember

- `&S::m` with a qualified name forms a pointer to member; `&(S::m)` does not.
- Write `(obj.*pmf)(args)` and `(ptr->*pmf)(args)`; the parentheses are required.
- `T Base::*` converts implicitly to `T Derived::*`; the other direction needs `static_cast` and a matching dynamic type.
- No implicit conversion goes through an inaccessible, ambiguous or virtual base.
- `&Derived::inherited` has the type of the declaring class, `T Base::*`.
- Member function pointers to virtual functions still dispatch virtually.
- Sizes and encodings are ABI choices: on Itanium, an offset with null `-1`, and a two-word pair for functions.
- `std::invoke` and `std::mem_fn` make member pointers callable with objects, pointers, smart pointers and `std::ref`; ranges projections use them.
- Overloaded members need a target type; never take the address of a standard library member function.

## Concept Map Outline

- **Pointers to members:** A path to a member of some class, applied to an object later with .* or ->*.
  - **Forming and applying:** &S::m with a qualified name, used as obj.*pm or ptr->*pm.
    - **Qualified name only:** &(S::m) or &m inside a member gives an ordinary pointer to this object's member.
    - **Call parentheses:** Write (obj.*pmf)(args); obj.*pmf(args) parses as obj.*(pmf(args)).
    - **Value category:** obj.*pm is an lvalue for an lvalue object and an xvalue for an rvalue object.
    - **Not pointable:** Static members give plain pointers; reference members and bit-fields cannot be pointed to.
  - **Conversions:** They run from base to derived, the reverse of object pointers.
    - **Base to derived:** T B::* converts implicitly to T D::* because D contains every member of B.
    - **Derived to base:** Needs static_cast; using it on an object lacking the member is undefined behavior.
    - **Forbidden bases:** No conversion through an inaccessible, ambiguous or virtual base.
    - **Declaring class type:** &D::x for a member of B has type int B::*.
  - **Virtual functions:** A pointer to a virtual function dispatches on the dynamic type when called.
    - **No non-virtual form:** Only a qualified call like b.B::f() suppresses dispatch; member pointers cannot.
  - **Representation:** Implementation practice only; the standard fixes no size or layout.
    - **Itanium data pointer:** One ptrdiff_t holding the member offset, with -1 as the null value.
    - **Itanium function pointer:** Two words: function address or vtable offset, plus a this adjustment.
    - **Virtual flag:** Low bit of ptr on x86-64, low bit of adj on AArch64 including arm64 macOS.
    - **MSVC:** Size depends on the inheritance model of the class.
  - **invoke and projections:** Library wrappers make member pointers ordinary callables.
    - **std::invoke:** Accepts objects, pointers, smart pointers and reference_wrapper; data members return references.
    - **std::mem_fn:** Wraps a member pointer in a reusable function object.
    - **Projections:** ranges::sort(v, {}, &P::age) compares by a field through std::invoke.
  - **Overloaded members:** An overload set has no type, so the target type selects the member.
    - **Target type:** A typed variable, parameter or static_cast picks the overload; auto cannot.
    - **Library members:** Forming &std::string::size is unspecified and possibly ill-formed; use a lambda.
    - **Explicit object (C++23):** &S::f for f(this const S&) is an ordinary function pointer.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.mptr.oper], [expr.call])

Is the initialization of `r` well-formed?

```cpp
struct S { int f() { return 1; } };

int main() {
  S s;
  int (S::*pf)() = &S::f;
  int r = s.*pf();
  return r;
}
```

A. Well-formed: it calls `s.f()` and `r` is 1
B. Ill-formed: it parses as `s.*(pf())`, and `pf` cannot be called on its own
C. Well-formed, but it is undefined behavior because `pf` is called without an object
D. Ill-formed: `.*` cannot be used with member functions, only `->*`

**Answer (B):** Ill-formed: it parses as `s.*(pf())`, and `pf` cannot be called on its own

**Why:** The pointer-to-member operators bind more loosely than the function call postfix operator, so `s.*pf()` means `s.*(pf())`. A pointer to member function is not callable by itself, and both GCC and Clang reject the call. The correct spelling is `(s.*pf)()`. Both `.*` and `->*` work with member function pointers; `->*` is for a pointer to the object.

### Question 2 [warmup] ([expr.mptr.oper], [class.virtual], [expr.call])

What does this program print?

```cpp
#include <cstdio>

struct B { virtual void f() { std::puts("B::f"); } };
struct D : B { void f() override { std::puts("D::f"); } };

int main() {
  void (B::*pf)() = &B::f;
  D d;
  B* bp = &d;
  (bp->*pf)();
}
```

A. `D::f`
B. `B::f`, because the pointer was formed from `&B::f`
C. Unspecified: it depends on how the ABI encodes virtual member pointers
D. Nothing: it is ill-formed to take the address of a virtual function

**Answer (A):** `D::f`

**Why:** A pointer to a virtual member function designates the virtual function, not one particular definition. Calling it through an object performs the same dispatch as `bp->f()`, so the final overrider for the dynamic type `D` runs. Naming `B::f` in `&B::f` only forms the pointer; only a qualified call such as `bp->B::f()` suppresses dispatch. The ABI encoding differs between platforms, but the behaviour is specified.

### Question 3 [warmup] ([conv.mem], [expr.static.cast])

Which declaration is ill-formed?

```cpp
struct B { int x; };
struct D : B { int y; };

int D::* p1 = &B::x;                       // #1
int B::* p2 = &D::y;                       // #2
int B::* p3 = static_cast<int B::*>(&D::y); // #3
```

A. #1 only
B. #1 and #3
C. #2 only
D. None

**Answer (C):** #2 only

**Why:** Pointers to members convert in the opposite direction from object pointers. Every member of `B` is a member of `D`, so `int B::*` converts implicitly to `int D::*`, which makes #1 fine. `y` exists only in `D`, so going from `int D::*` to `int B::*` needs a `static_cast`; #3 is well-formed and #2 is ill-formed. Using `p3` on an object that is not really a `D` would be undefined behavior.

### Question 4 [tricky] ([expr.unary.op], [conv.mem])

What is `decltype(&D::x)`?

```cpp
struct B { int x; };
struct D : B {};
```

A. `int D::*`
B. `int*`
C. Ill-formed: `x` is not declared in `D`
D. `int B::*`

**Answer (D):** `int B::*`

**Why:** When `&` is applied to a qualified name of a non-static member, the result's class is the class in which the member is declared, not the class named in the qualifier. So `&D::x` has type `int B::*`, which then converts implicitly to `int D::*` if needed. The difference shows up in template argument deduction, where a parameter `int C::*` deduces `C = B`.

### Question 5 [tricky] ([conv.mem])

Is this declaration well-formed?

```cpp
struct V { int v; };
struct D : virtual V {};

int D::* p = &V::v;
```

A. Well-formed: base-to-derived member pointer conversion is always implicit
B. Ill-formed: the conversion goes through a virtual base
C. Well-formed, but using `p` is undefined behavior
D. Ill-formed: `V` is an inaccessible base

**Answer (B):** Ill-formed: the conversion goes through a virtual base

**Why:** [conv.mem] forbids the conversion from `T B::*` to `T D::*` when `B` is inaccessible, ambiguous, or a virtual base of `D`. A virtual base can sit at a different offset in each most-derived object, so the pointer could not be adjusted by a fixed amount. The base here is public, so the fourth option names the wrong reason; with a non-virtual base the first option would be right.

### Question 6 [tricky] ([func.invoke], [func.require], [expr.mptr.oper])

Given `struct P { int age; }; P p;`, what is `decltype(std::invoke(&P::age, std::move(p)))`?

A. `int`
B. `int&`
C. `int&&`
D. `const int&`

**Answer (C):** `int&&`

**Why:** For a pointer to data member, INVOKE is `t1.*f` when `t1` is an object, and `.*` on a data member gives an xvalue when the object is an xvalue. `std::invoke` returns that expression's type, so the result is `int&&`. With the lvalue `p` it would be `int&`, which is the tempting answer. It is never a copy, so `int` is wrong too, and no `const` is added.

### Question 7 [standardese] ([expr.mptr.oper], [expr.static.cast])

What does the standard say about evaluating `f()`?

```cpp
struct B { int b = 0; };
struct D1 : B { int d1 = 1; };
struct D2 : B { int d2 = 2; };

int f() {
  int B::* p = static_cast<int B::*>(&D1::d1);
  D2 d;
  B& br = d;
  return br.*p;
}
```

A. Undefined behavior
B. It returns 1
C. Ill-formed: the `static_cast` from `int D1::*` is not allowed
D. It returns 2, because `d1` and `d2` have the same offset

**Answer (A):** Undefined behavior

**Why:** The `static_cast` is valid because `B` is a non-virtual, accessible base of `D1`. But [expr.mptr.oper] says that if the dynamic type of the object does not contain the member the pointer refers to, the behavior is undefined. The dynamic type here is `D2`, which has no `d1`. On common ABIs the offset happens to land on `d2`, which is why the last option can appear to work, but that is not a result the standard gives.

### Question 8 [standardese] ([namespace.std], [member.functions])

What does the C++23 standard say about this declaration?

```cpp
#include <string>

auto p = &std::string::size;
```

A. It is well-formed and portable: `size` is a public member function
B. It is ill-formed: library member functions are always overloaded
C. Its behavior is unspecified, and it may be ill-formed
D. It is undefined behavior only if `p` is called

**Answer (C):** Its behavior is unspecified, and it may be ill-formed

**Why:** [namespace.std] says that forming a pointer to member designating a standard library non-static member function makes the behavior of the program unspecified, possibly ill-formed. Implementations may add overloads, default arguments or extra parameters to library members, so the address need not mean the same thing everywhere. GCC and Clang accept it today, which is why the first option is tempting. Use a lambda such as `[](const std::string& s) { return s.size(); }` instead.

# RAII and Resource Management

> Bind every resource invariant to an object lifetime so deterministic destructors, stack unwinding, and the Rule of Zero eliminate leaks by construction.

- **Source:** C++ Atlas (https://cppatlas.com/topics/raii-and-resource-management)
- **Track:** Classes
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [basic.stc.auto] (https://eel.is/c++draft/basic.stc.auto), [class.dtor] (https://eel.is/c++draft/class.dtor), [except.ctor] (https://eel.is/c++draft/except.ctor), [class.copy.ctor] (https://eel.is/c++draft/class.copy.ctor), [class.copy.assign] (https://eel.is/c++draft/class.copy.assign), [smartptr] (https://eel.is/c++draft/smartptr), [thread.lock.scoped] (https://eel.is/c++draft/thread.lock.scoped)
- **cppreference links:** [RAII](https://en.cppreference.com/w/cpp/language/raii), [The rule of three/five/zero](https://en.cppreference.com/w/cpp/language/rule_of_three), [Destructors](https://en.cppreference.com/w/cpp/language/destructor), [Exceptions](https://en.cppreference.com/w/cpp/language/exceptions), [std::unique_ptr](https://en.cppreference.com/w/cpp/memory/unique_ptr), [std::shared_ptr](https://en.cppreference.com/w/cpp/memory/shared_ptr), [std::scoped_lock](https://en.cppreference.com/w/cpp/thread/scoped_lock), [std::exchange](https://en.cppreference.com/w/cpp/utility/exchange)
- **Prerequisites:** constructors-and-initialization-order, copy-and-move

Resource Acquisition Is Initialization (RAII) is C++'s foundational pattern for making leaks impossible by construction. Despite the awkward historical name, the rule has nothing to do with memory alone and everything to do with **invariants**: every acquisition of a finite resource—heap allocations, file descriptors, mutex locks, database transactions, or temporary flag mutations—must be paired with an automatic object whose lifetime governs that resource.

## Invariants bound to object lifetime

Manual `acquire()` / `release()` pairs fail whenever a function grows an early `return`, a `break`, or a call that throws an exception. RAII replaces cleanup branches across every exit path with one invariant maintained inside a class boundary: the constructor acquires the resource (or throws before the object's lifetime ever begins), and the destructor releases it deterministically when the enclosing scope ends (`[basic.stc.auto]`).

> **Mental model.** An object either owns a valid resource handle or never finished constructing. Because C++ guarantees destructors run on normal scope exit, early return, and exception unwinding alike, cleanup becomes a structural property of lexical scope rather than caller discipline.

That principle scales beyond pointers to arbitrary state transitions. A `std::scoped_lock` acquires one or more mutexes in its constructor and unlocks them in reverse on exit without deadlock (`[thread.lock.scoped]`). A state-saving guard can capture a numeric flag or locale on construction and restore it unconditionally when destroyed.

## Deterministic destruction and stack unwinding

C++ defines exact destruction order at every boundary (`[class.dtor]`):

- **Block scope:** automatic variables are destroyed in the exact reverse order their constructors completed.
- **Class members and bases:** non-static data members are destroyed in reverse declaration order, followed by direct non-virtual base classes in reverse base-specifier order, and finally virtual bases in reverse initialization order.

Stack unwinding preserves this guarantee when exceptions fly.

> **Standardese.** Under `[except.ctor]`, if an exception exits a constructor before its closing brace, the object's lifetime never began, so its own destructor does not run; however, every already-constructed base subobject and data member is destroyed immediately in reverse order.

```cpp
#include <stdexcept>

struct Channel {
    explicit Channel(int id) {
        if (id < 0) throw std::runtime_error("invalid channel");
    }
    ~Channel() = default;
};

struct Bridge {
    Channel rx;
    Channel tx;
    Bridge(int in_id, int out_id) : rx(in_id), tx(out_id) {}
    // If tx throws, ~rx() runs automatically; ~Bridge() never executes.
};
```

In contrast, letting an exception escape a destructor is catastrophic. Since C++11, user-declared destructors are implicitly `noexcept(true)` unless explicitly annotated `noexcept(false)` or inheriting a throwing member/base destructor (`[class.dtor]`). Throwing out of a `noexcept` destructor—or throwing a second exception while stack unwinding is already active—invokes `std::terminate()` immediately. Keep destructors non-throwing, logging or swallowing teardown failures safely when necessary.

## The Rule of Zero and the Rule of Five

Separating business logic from low-level ownership yields two complementary rules that govern special member functions.

The **Rule of Zero** applies to virtually all application classes: compose your type from existing RAII handles (`std::string`, `std::vector`, `std::unique_ptr`, `std::jthread`) and declare *no* destructor, copy constructor, copy assignment operator, move constructor, or move assignment operator. The compiler automatically synthesizes optimal, exception-safe special members by forwarding to each member.

The **Rule of Five** applies strictly to low-level wrapper classes that directly manage a raw resource handle (such as an OS file descriptor). Because the compiler cannot guess how to duplicate or relinquish a raw `int` handle, declaring a custom destructor requires explicitly specifying all five special members (`~T`, copy ctor, copy assign, move ctor, move assign)—either implementing or `= delete`-ing copying while writing a `noexcept` move with `std::exchange`.

```cpp
#include <utility>
#include <vector>

class UniqueFd {
    int fd_ = -1;
public:
    explicit UniqueFd(int fd = -1) noexcept : fd_(fd) {}
    ~UniqueFd() {
        if (fd_ >= 0) { /* close(fd_) */ }
    }

    UniqueFd(const UniqueFd&) = delete;
    UniqueFd& operator=(const UniqueFd&) = delete;

    UniqueFd(UniqueFd&& other) noexcept
        : fd_(std::exchange(other.fd_, -1)) {}

    UniqueFd& operator=(UniqueFd&& other) noexcept {
        if (this != &other) {
            if (fd_ >= 0) { /* close(fd_) */ }
            fd_ = std::exchange(other.fd_, -1);
        }
        return *this;
    }
};

struct Session { // Rule of Zero: inherits move-only semantics cleanly
    UniqueFd socket;
    std::vector<int> backlog;
};
```

> **Pitfall.** Writing `~Widget() = default;` inside a class body counts as a **user-declared destructor** (`[class.copy.ctor]`). That single line silently suppresses implicit move constructor and move assignment generation, causing moves on `Widget` to fall back to expensive copies, and marks implicit copy generation deprecated (`[depr.impldec]`).

## Ownership vocabulary: unique_ptr, shared_ptr, and locks

Express ownership intent directly in the type system so readers and compilers verify lifetime contracts at compile time. Choosing the right standard handle clarifies both lifetime semantics and runtime cost:

| Handle type | Ownership model | Overhead vs raw handle | Typical use case |
| --- | --- | --- | --- |
| `std::unique_ptr<T, D>` | Exclusive, move-only | Zero with stateless deleter | Polymorphic objects, C handles |
| `std::shared_ptr<T>` | Shared reference count | Control block + atomic count | Graph/async shared lifetimes |
| `std::weak_ptr<T>` | Non-owning observer | Shares control block existence | Cache entries, breaking cycles |
| `std::scoped_lock<Ms...>` | Lexical multi-mutex guard | Stack-only RAII frame | Deadlock-free critical sections |

For C APIs such as `std::FILE*`, prefer a stateless functor deleter over a function pointer. Passing `&std::fclose` as the deleter type `int(*)(std::FILE*)` stores an extra 8-byte pointer inside every `std::unique_ptr`, whereas a stateless callable `struct FileCloser` collapses to zero bytes via empty base optimization or `[[no_unique_address]]`:

```cpp
#include <cstdio>
#include <memory>

struct FileCloser {
    void operator()(std::FILE* f) const noexcept {
        if (f) std::fclose(f);
    }
};

using UniqueFile = std::unique_ptr<std::FILE, FileCloser>;
static_assert(sizeof(UniqueFile) == sizeof(std::FILE*));
```

Always allocate with `std::make_unique` or `std::make_shared` rather than bare `new`. Beyond removing `new`/`delete` from user code, `std::make_shared` combines the control block and managed object into one allocation, and before C++17 calling `f(std::unique_ptr<A>(new A), may_throw())` risked leaking `A` if `may_throw()` ran between `new A` and `unique_ptr` construction.

## Failure modes: self-assignment, noexcept, and premature exit

Even well-written RAII wrappers break along three edge boundaries. First, **self-move assignment** (`a = std::move(a)`) and **self-copy assignment** (`a = a`) can occur in generic algorithms (`std::sort`, `std::swap` fallbacks). Guard resource release in `operator=` or implement copy-and-swap / move-and-swap so self-assignment remains safe. Second, mark move operations `noexcept`: containers like `std::vector` rely on `std::move_if_noexcept` to preserve the strong exception guarantee, falling back to `O(N)` copies if a move constructor can throw. Third, avoid abrupt termination calls (`std::abort()`, `std::_Exit()`, or `std::exit()` while stack locals remain live): `std::exit()` runs `thread_local` and static destructors, **never** unwinding automatic stack frames (`[basic.start.term]`). Return cleanly from `main` instead so every scope unwinds.

## What to remember

- Bind every resource invariant—not just heap memory—to an object whose constructor establishes validity and whose destructor releases it.
- Destructors run in reverse construction order; if a constructor throws, already-constructed bases and members unwind while the enclosing destructor does not run.
- Destructors are implicitly `noexcept`; never allow exceptions to escape a destructor.
- Follow the **Rule of Zero** in domain classes; follow the **Rule of Five** only in dedicated single-resource wrappers, using `std::exchange` and `noexcept` on moves.
- Never write `~T() = default;` gratuitously—a user-declared destructor suppresses implicit move operations.

## Concept Map Outline

- **RAII & Resource Safety:** Binding resource invariants to object lifetimes guarantees deterministic cleanup across every exit path.
  - **Core Principle:** Constructors establish resource invariants and destructors release them at lexical scope exit.
    - **Invariant Acquisition:** A successfully constructed RAII object always holds either a valid resource or a safe empty state.
    - **Scope-Exit Release:** Cleanup fires uniformly on fallthrough, early return, break, and exception unwinding.
    - **Non-Memory Resources:** RAII manages file descriptors, mutexes, sockets, transactions, and temporary state guards alike.
  - **Destruction Rules:** C++ prescribes strict reverse teardown ordering and implicit noexcept on destructors.
    - **Reverse Order:** Locals, members, and bases are destroyed in exact reverse order of construction completion.
    - **Implicit noexcept:** Destructors are implicitly noexcept(true) since C++11 unless explicitly overridden or inheriting throwing ones.
    - **std::terminate Trap:** Allowing an exception to escape a noexcept destructor immediately calls std::terminate.
  - **Exception Unwinding:** Exceptions unwind only completely constructed objects and subobjects.
    - **Completed Subobjects:** Every base or member whose constructor finished before a throw is destroyed automatically.
    - **No Partial Destructor:** When a class constructor throws, that class's own destructor never runs because lifetime never began.
    - **No Abrupt Exit Unwind:** Calling std::exit or std::abort bypasses automatic stack frame destructors.
  - **Special Members:** Ownership design separates zero-boilerplate composition from custom resource handles.
    - **Rule of Zero:** Domain classes hold standard RAII members and declare zero custom special member functions.
    - **Rule of Five:** Low-level resource wrappers declaring a destructor must explicitly define or delete copy and move operations.
    - **Suppressed Moves:** Any user-declared destructor—even = default—suppresses compiler-generated move operations.
    - **std::exchange Moves:** Transfer handles cleanly with std::exchange(other.handle, invalid) and mark moves noexcept.
  - **Standard Vocabulary:** Standard library smart pointers and lock guards encode ownership contracts directly in types.
    - **unique_ptr Deleters:** Stateless functor deleters preserve single-pointer size whereas function-pointer deleters add storage overhead.
    - **shared_ptr & weak_ptr:** Use shared ownership sparingly with make_shared and break reference cycles with weak_ptr.
    - **scoped_lock Guards:** Acquire multiple mutexes atomically without deadlock and release them automatically at scope exit.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.stc.auto], [class.dtor])

In what order are local variables and class data members destroyed when a scope exits?

A. Alphabetical by identifier name for members, declaration order for locals
B. Reverse order of construction completion for locals, and reverse declaration order for class members
C. Forward declaration order so earlier handles close before later ones
D. Unspecified order unless wrapped inside std::tuple

**Answer (B):** Reverse order of construction completion for locals, and reverse declaration order for class members

**Why:** Under [basic.stc.auto] and [class.dtor], block-scope objects unwind in exact reverse order of construction completion, while class members are destroyed in reverse order of declaration inside the class definition.

### Question 2 [warmup] ([class.copy.ctor], [class.copy.assign])

What is the hidden consequence of adding `~Packet() = default;` to a struct that holds a std::vector<std::byte>?

```cpp
struct Packet {
    std::vector<std::byte> payload;
    ~Packet() = default;
};
```

A. Nothing changes; = default leaves all implicitly generated special members identical
B. The vector cannot be destroyed unless std::destroy_at is called manually
C. The struct becomes non-copyable until copy operations are also defaulted
D. Implicit move constructor and move assignment are suppressed, so moves silently fall back to copying payload

**Answer (D):** Implicit move constructor and move assignment are suppressed, so moves silently fall back to copying payload

**Why:** Under [class.copy.ctor] and [class.copy.assign], any user-declared destructor—even `= default;`—prevents implicit declaration of the move constructor and move assignment operator, turning `std::move(pkt)` into a copy.

### Question 3 [tricky] ([except.ctor])

Assume Part(1) succeeds and Part(2) throws std::runtime_error during construction of Assembly. Which destructors run?

```cpp
struct Part {
    explicit Part(int id);
    ~Part();
};
struct Assembly {
    Part first;
    Part second;
    Assembly() : first(1), second(2) {}
    ~Assembly();
};
```

A. Only ~Part() for first runs; ~Part() for second and ~Assembly() do NOT run
B. ~Part() for both first and second run, followed by ~Assembly()
C. Only ~Assembly() runs to clean up both members
D. No destructors run because the expression failed before Assembly existed

**Answer (A):** Only ~Part() for first runs; ~Part() for second and ~Assembly() do NOT run

**Why:** Under [except.ctor], because Assembly's constructor exited via an exception, Assembly's lifetime never began and ~Assembly() never runs. Every already-completed subobject (here only first) is destroyed immediately.

### Question 4 [tricky] ([unique.ptr.single])

Why does `std::unique_ptr<std::FILE, FileCloser>` (with stateless functor `FileCloser`) typically match `sizeof(std::FILE*)`, whereas `std::unique_ptr<std::FILE, int(*)(std::FILE*)>` is larger?

```cpp
struct FileCloser {
    void operator()(std::FILE* f) const noexcept { if (f) std::fclose(f); }
};
using P1 = std::unique_ptr<std::FILE, FileCloser>;
using P2 = std::unique_ptr<std::FILE, int(*)(std::FILE*)>;
```

A. std::unique_ptr uses std::shared_ptr's control block whenever a function pointer is passed
B. Function pointers disable move semantics, forcing std::unique_ptr to allocate a flag
C. P2 must store the runtime function pointer address inside the smart pointer, while stateless FileCloser takes zero bytes via empty-base / [[no_unique_address]] optimization
D. FileCloser deletes the pointer at compile time during constexpr evaluation

**Answer (C):** P2 must store the runtime function pointer address inside the smart pointer, while stateless FileCloser takes zero bytes via empty-base / [[no_unique_address]] optimization

**Why:** A function pointer type `int(*)(std::FILE*)` is stateful runtime data (different pointers share the same type), so unique_ptr must store it. A stateless functor encodes the deleter in the type itself and occupies zero extra bytes.

### Question 5 [standardese] ([class.dtor], [except.spec])

What happens in C++23 if a user-declared destructor `~Guard() { cleanup(); }` (with no exception specification) throws an exception at runtime during normal scope exit?

```cpp
struct Guard {
    ~Guard() { throw std::runtime_error("boom"); }
};
```

A. The exception propagates normally to the caller's catch block because noexcept was not written
B. std::terminate() is called because user-declared destructors are implicitly noexcept(true)
C. The compiler rejects ~Guard() at compile time whenever throw appears inside a destructor
D. Only throws during stack unwinding terminate; normal scope-exit throws propagate

**Answer (B):** std::terminate() is called because user-declared destructors are implicitly noexcept(true)

**Why:** Since C++11 ([class.dtor] / [except.spec]), a destructor with no explicit exception specification inherits the exception specification of an implicitly declared destructor—which is `noexcept(true)` unless a base or member destructor can throw. Exiting it via exception calls std::terminate().

### Question 6 [standardese] ([depr.impldec], [class.copy.ctor])

Suppose `Wrapper` declares a custom destructor `~Wrapper() { ... }` and omits copy/move declarations. Why does copying `Wrapper` still compile today despite violating the Rule of Five?

```cpp
struct Wrapper {
    int fd = -1;
    ~Wrapper() { /* ... */ }
};
```

A. Implicit copy operations are forbidden; copying Wrapper only works via memcpy
B. Move operations are still generated instead of copy operations
C. User-declared destructors only suppress special members if virtual
D. Implicit generation of copy constructor and copy assignment is deprecated when a user-declared destructor exists, though still permitted for backward compatibility

**Answer (D):** Implicit generation of copy constructor and copy assignment is deprecated when a user-declared destructor exists, though still permitted for backward compatibility

**Why:** Under [depr.impldec] and [class.copy.ctor], declaring a destructor suppresses implicit move operations outright, whereas implicit copy constructor and copy assignment generation remain allowed—but explicitly deprecated.

---

# Track: Templates

Forwarding references, SFINAE, C++20 concept subsumption and C++23 explicit object parameters.

# Template instantiation and specialization

> A template is a recipe, and a specialization is what you get for one set of arguments, either cooked by the compiler on demand or written by you in advance. Knowing when the compiler cooks, and what your hand-written versions replace, explains lazy members, extern template and the classic function-specialization surprise.

- **Source:** C++ Atlas (https://cppatlas.com/topics/template-instantiation-and-specialization)
- **Track:** Templates
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [temp.spec] (https://eel.is/c++draft/temp.spec), [temp.inst] (https://eel.is/c++draft/temp.inst), [temp.point] (https://eel.is/c++draft/temp.point), [temp.explicit] (https://eel.is/c++draft/temp.explicit), [temp.expl.spec] (https://eel.is/c++draft/temp.expl.spec), [temp.spec.partial] (https://eel.is/c++draft/temp.spec.partial), [temp.over] (https://eel.is/c++draft/temp.over)
- **cppreference links:** [Explicit (full) template specialization](https://en.cppreference.com/w/cpp/language/template_specialization), [Partial template specialization](https://en.cppreference.com/w/cpp/language/partial_specialization), [Class template (explicit instantiation)](https://en.cppreference.com/w/cpp/language/class_template), [Function template](https://en.cppreference.com/w/cpp/language/function_template), [Variable template](https://en.cppreference.com/w/cpp/language/variable_template)
- **Prerequisites:** one-definition-rule, translation-units-and-linkage

## The one idea

A template is not code; it is a recipe for code. Every distinct set of template arguments names a **specialization**: `Box<int>` and `Box<double>` are two specializations of `Box`, as unrelated to each other as two hand-written classes. A specialization comes into existence in one of two ways. Either the compiler **instantiates** it from the template, implicitly because you used it or explicitly because you asked, or you supply its definition yourself as an **explicit specialization** or a **partial specialization**.

The rest of the topic is about the consequences. The compiler instantiates as little as it can get away with, so code that would not compile is harmless until something needs it. A hand-written specialization replaces the recipe for its arguments, so it must be visible before anyone asks the compiler to cook. And for function templates, hand-written specializations do not compete in overload resolution, which surprises nearly everyone once.

> **Mental model.** Overload resolution and partial specialization matching choose a *recipe*. An explicit specialization is a pre-cooked dish for one exact order of that recipe. It is served only after the recipe has already been chosen.

## Implicit instantiation is lazy

Using `Box<int>` in a way that needs a complete type implicitly instantiates the class. That instantiates the *declarations* of its members, including member types, data members and function signatures, but not the *definitions* of its member functions, its default arguments, its member classes or its static data members. A member function body is instantiated only when the function is odr-used, or otherwise needed.

```cpp
template<class T> struct Box {
  T value;
  void bad() { value.frobnicate(); }  // checked only if bad() is used
  using ptr = T*;                     // a declaration: instantiated with the class
};

Box<int> ok{1};          // fine: Box<int>::bad is declared, never defined
Box<int&>* p = nullptr;  // fine: a pointer to Box<int&> needs no complete type
// ok.bad();             // error: int has no member frobnicate
// int x; Box<int&> r{x}; // error: forming a pointer to int& in 'using ptr'
```

This laziness is a feature the standard library depends on. `std::vector<T>` has a copy constructor that would fail for move-only `T`, and `std::optional<T>` has comparison operators that require `T` to be comparable. Neither matters until you call them. Naming a specialization without requiring completeness, as in a pointer or reference to it, does not instantiate the class at all.

Templates are also checked at definition time for things that do not depend on the parameters, so laziness does not mean anything goes. That first-phase check is the subject of the topic on dependent names and two-phase lookup.

## Points of instantiation

A specialization is instantiated as though at a particular place in the translation unit, its **point of instantiation**. For a function template specialization used inside a namespace-scope declaration, that point is immediately after the declaration. For a class template specialization, it is immediately before the namespace-scope declaration that needed it. Names that depend on the template parameters are looked up, by argument-dependent lookup, as of that point.

The standard adds a twist for function templates: the end of the translation unit is *also* a point of instantiation. If two points give the specialization different meanings, the program is ill-formed, no diagnostic required.

```cpp
namespace n {
  struct A {};
  int score(const A&) { return 1; }
}
template<class T> int pick(T t) { return score(t); }

int first = pick(n::A{});  // a point of instantiation of pick<n::A> follows this line

namespace n { int score(A&) { return 2; } }  // a better match for the lvalue t
// The end of the file is another point of instantiation, where score(A&) wins.
// Ill-formed, no diagnostic required. GCC 16 and Clang 21 both set first to 2,
// because they actually instantiate function bodies at the end of the file.
```

> **Standardese.** [temp.point] lets a function template specialization have several points of instantiation in one translation unit, always including the end of the unit, and makes the program ill-formed, no diagnostic required, if they would give the specialization different meanings under the one-definition rule.

## Explicit instantiation and `extern template`

An **explicit instantiation definition** forces a specialization to be instantiated here: `template struct Box<int>;` or `template int twice<int>(int);`. For a class, it instantiates every member that has been defined at that point, which defeats the laziness above. An **explicit instantiation declaration**, spelled with `extern`, promises that a definition exists in some other translation unit and suppresses implicit instantiation of the entity's definition in this one.

```cpp
template<class T> T twice(T x) { return x + x; }

template int twice<int>(int);       // explicit instantiation definition
template double twice(double);      // the argument can be deduced
extern template long twice(long);   // declaration: instantiate it elsewhere

// template struct Box<int>;   // with Box from above: error, this instantiates bad()
```

The usual pattern puts `extern template` in a header after the template's definition and a matching explicit instantiation definition in exactly one source file, so that dozens of translation units stop compiling and emitting the same code. Two details matter. First, the suppression does not apply to inline functions, `constexpr` functions, or functions whose return type is deduced, so member functions defined inside the class body may still be instantiated for inlining. Second, if you use the entity and no explicit instantiation definition exists anywhere, the program is ill-formed, no diagnostic required. In practice that shows up as an undefined symbol at link time.

> **Pitfall.** An explicit instantiation definition checks every member body. With GCC's standard library, `template class std::vector<std::unique_ptr<int>>;` fails to compile, because it instantiates the copy constructor that implicit use would never touch. Explicitly instantiate only types that support every member.

## Explicit specialization

An explicit specialization, introduced by `template<>`, provides the definition for one exact set of arguments. For a class template it is a completely separate class: it inherits no members from the primary template, and it may have a different layout, different members, or no definition at all. You can also explicitly specialize a single member of an implicitly instantiated class.

```cpp
template<class T> struct Hash { static int of(const T&) { return 0; } };

template<> struct Hash<bool> {                 // an unrelated class with its own members
  static int of(bool b) { return b ? 1 : 0; }
};
template<> int Hash<char>::of(const char& c) { return c; }  // just one member
```

The ordering rule is strict. An explicit specialization must be declared before the first use that would cause an implicit instantiation, in every translation unit where such a use occurs. Within one file, compilers catch the violation.

```cpp
template<class T> struct Traits { static constexpr int id = 0; };
int f() { return Traits<int>::id; }    // implicitly instantiates Traits<int>
// template<> struct Traits<int> { static constexpr int id = 1; };
// error: specialization of 'Traits<int>' after instantiation
```

Across translation units nobody catches it. If one file sees the specialization and another file instantiates the primary template for the same arguments, the program is ill-formed with no diagnostic required, and the linker typically keeps whichever definition it sees first. Declare specializations in the same header as the primary template, or in a header that every user must include.

## Partial specialization of class and variable templates

A partial specialization keeps some parameters and constrains the shape of the arguments. Only class templates and, since C++14, variable templates can be partially specialized. When a specialization is needed, the compiler matches the arguments against every partial specialization; if one matches, the most specialized of the matching ones is used, and if none matches, the primary template is used. The ranking itself is covered in the topic on partial ordering of templates.

```cpp
template<class T, class U> struct Pair        { static constexpr int k = 0; };
template<class T>          struct Pair<T, T>  { static constexpr int k = 1; };
template<class T, class U> struct Pair<T*, U> { static constexpr int k = 2; };

static_assert(Pair<int, long>::k == 0);
static_assert(Pair<int, int>::k == 1);
static_assert(Pair<int*, long>::k == 2);
// Pair<int*, int*>::k: error, both partial specializations match equally well

template<class T> constexpr bool is_ptr = false;
template<class T> constexpr bool is_ptr<T*> = true;
template<class T> constexpr bool is_ptr<T* const> = true;  // top-level const is part of the type
static_assert(is_ptr<int* const>);
```

A partial specialization must be more specialized than the primary template, cannot have default template arguments, and, like an explicit specialization, must be declared before the use that would select it. Matching is exact on types: `int* const` does not match `T*`, which is why the standard traits strip cv-qualifiers first.

## Function templates: overload instead

A function template cannot be partially specialized at all. Writing `template<class T> void f<T*>(T*);` is an error. The language already has a tool for that job, overloading, and two overloaded templates followed by partial ordering cover every case partial specialization would.

Explicit specialization of a function template is allowed, but it is not an overload. Overload resolution considers only the primary templates and ordinary functions. Once a primary template wins, its explicit specialization, if one exists for the deduced arguments, supplies the body. Which primary template a specialization belongs to is decided at the point where you declare it, by the templates visible there. Peter Dimov and Dave Abrahams made this famous with two programs that differ only in the order of declarations.

```cpp
#include <cstdio>

template<class T> void f(T)    { std::puts("f(T)"); }     // (a)
template<class T> void f(T*)   { std::puts("f(T*)"); }    // (b)
template<>        void f(int*) { std::puts("f<int*>"); }  // specializes (b), the better match

template<class T> void g(T)    { std::puts("g(T)"); }     // (a)
template<>        void g(int*) { std::puts("g<int*>"); }  // only (a) exists yet: specializes it
template<class T> void g(T*)   { std::puts("g(T*)"); }    // (b)

int main() {
  int* p = nullptr;
  f(p);  // (b) wins overload resolution, its specialization runs: prints f<int*>
  g(p);  // (b) wins again, but the specialization belongs to (a): prints g(T*)
}
```

The cure is to stop specializing function templates. Write an ordinary non-template overload, which takes part in overload resolution and beats a template on an exact match. If you need partial-specialization behaviour, have the function template forward to a static member of a class template and partially specialize the class.

> **Pitfall.** Specializing a standard library function template in namespace `std` is undefined behavior since C++20. Customization goes through overloads found by argument-dependent lookup, or through specializing class templates such as `std::hash`.

## What to remember

- Each set of template arguments names a specialization; it is either instantiated from the template or written by hand.
- Implicitly instantiating a class instantiates member declarations only; bodies, default arguments and static data members wait until used.
- A function template specialization also has a point of instantiation at the end of the file, and meaning that differs between points is ill-formed, no diagnostic required.
- `template struct X<int>;` instantiates every defined member; `extern template` suppresses implicit instantiation of non-inline definitions and needs a definition somewhere.
- An explicit specialization must be declared before the first use that would instantiate it, in every translation unit, or the program is ill-formed with no diagnostic required.
- Only class and variable templates can be partially specialized; the most specialized matching one wins.
- Function template specializations never take part in overload resolution; they attach to the primary visible where they are declared. Overload instead.

## Concept Map Outline

- **Instantiation and specialization:** Each argument set names a specialization, instantiated from the template or written by hand.
  - **Implicit instantiation:** Happens on demand when a use needs the definition.
    - **Declarations only:** A class instantiation creates member declarations, not member function bodies.
    - **Bodies when used:** A member function, default argument or static member is instantiated only if needed.
    - **Pointers need nothing:** Naming Box<T>* or Box<T>& does not instantiate the class.
  - **Point of instantiation:** Where dependent names are resolved as though the specialization were written.
    - **Function templates:** Right after the namespace-scope declaration that uses it, and also at end of file.
    - **Class templates:** Immediately before the namespace-scope declaration that needs it.
    - **Differing meanings:** If two points give different meanings, ill-formed, no diagnostic required.
  - **Explicit instantiation:** You tell the compiler to instantiate, or not to.
    - **template struct X<int>;:** Instantiates every member defined at that point, so all bodies must compile.
    - **extern template:** Suppresses implicit instantiation of non-inline definitions in this translation unit.
    - **Missing definition:** Used but never explicitly instantiated anywhere: ill-formed NDR, usually a link error.
  - **Explicit specialization:** template<> supplies the definition for one exact argument list.
    - **Unrelated class:** A full class specialization inherits no members from the primary template.
    - **Single member:** One member function of an implicit specialization can be specialized alone.
    - **Declare before use:** After an instantiating use, or missing in another TU: ill-formed NDR.
  - **Partial specialization:** Constrains the shape of arguments while keeping some parameters.
    - **Class and variable:** Allowed for class templates and, since C++14, variable templates only.
    - **Most specialized wins:** Among matching partial specializations; equal ones make the use ambiguous.
    - **Exact matching:** int* const does not match T*; cv-qualifiers are part of the type.
  - **Function templates:** No partial specialization; overload them instead.
    - **Not in overload resolution:** Only primaries compete; the winner's explicit specialization then supplies the body.
    - **Dimov/Abrahams:** A specialization attaches to the best primary visible where it is declared.
    - **Prefer overloads:** Use a plain overload, or forward to a partially specialized class template.

## Standardese Quiz Questions

### Question 1 [warmup] ([temp.inst])

Is this program well-formed?

```cpp
template<class T> struct Box {
  T value;
  void bad() { value.frobnicate(); }
};

int main() {
  Box<int> b{42};
  return b.value - 42;
}
```

A. Ill-formed: `int` has no member `frobnicate`
B. Ill-formed, no diagnostic required
C. Well-formed: the body of `bad` is never instantiated
D. Ill-formed: a class with member functions cannot be initialized with `{42}`

**Answer (C):** Well-formed: the body of `bad` is never instantiated

**Why:** Implicitly instantiating `Box<int>` instantiates the declarations of its members, so `void bad();` exists, but not the definitions of its member functions. The body of `bad` would be instantiated only if `bad` were used, and it is not. The first option is the error you would get from `b.bad();` or from an explicit instantiation definition of `Box<int>`. `Box<int>` is still an aggregate, because member functions do not affect that, so `{42}` initializes `value`.

### Question 2 [warmup] ([temp.spec.partial], [temp.fct], [temp.alias])

In C++23, which kinds of templates can be partially specialized?

A. Class templates only
B. Class templates and variable templates
C. Class templates, variable templates and function templates
D. Class templates and function templates
E. Class templates, variable templates and alias templates

**Answer (B):** Class templates and variable templates

**Why:** Class templates have always allowed partial specialization, and variable templates allow it since they were added in C++14. Function templates cannot be partially specialized: the language expects you to overload them instead, and partial ordering picks the more specialized overload. Alias templates cannot be specialized at all, neither fully nor partially.

### Question 3 [warmup] ([temp.spec.partial.match], [temp.expl.spec])

What does this program print?

```cpp
#include <cstdio>

template<class T> struct S       { static const char* name() { return "primary"; } };
template<class T> struct S<T*>   { static const char* name() { return "pointer"; } };
template<>        struct S<int*> { static const char* name() { return "int*"; } };

int main() {
  std::puts(S<int*>::name());
  std::puts(S<const int*>::name());
  std::puts(S<int* const>::name());
}
```

A. `int*`, `pointer`, `pointer`
B. `pointer`, `pointer`, `primary`
C. `int*`, `int*`, `pointer`
D. `int*`, `pointer`, `primary`

**Answer (D):** `int*`, `pointer`, `primary`

**Why:** `S<int*>` uses the explicit specialization, which is an exact match for those arguments. `S<const int*>` matches the partial specialization `S<T*>` with `T` deduced as `const int`. `S<int* const>` is a const pointer: the top-level `const` is part of the argument type, and `int* const` does not have the form `T*`, so the primary template is used. The tempting first option forgets that matching is on the exact type, cv-qualifiers included.

### Question 4 [tricky] ([temp.over], [temp.expl.spec], [temp.func.order])

What does this program print?

```cpp
#include <cstdio>

template<class T> void f(T)    { std::puts("f(T)"); }
template<>        void f(int*) { std::puts("f<int*>"); }
template<class T> void f(T*)   { std::puts("f(T*)"); }

int main() {
  int* p = nullptr;
  f(p);
}
```

A. `f<int*>`
B. `f(T*)`
C. `f(T)`
D. Ill-formed: the call is ambiguous

**Answer (B):** `f(T*)`

**Why:** When the explicit specialization is declared, only `f(T)` exists, so it is a specialization of that template with `T = int*`. Overload resolution then considers only the two primary templates; `f(T*)` is more specialized and wins, and it has no explicit specialization for `int`, so `f(T*)` runs. The tempting answer `f<int*>` is what you get if the specialization is declared after `f(T*)`, because it would then specialize the better template. Explicit specializations never take part in overload resolution themselves.

### Question 5 [tricky] ([temp.explicit], [temp.inst])

Is this translation unit well-formed?

```cpp
template<class T> struct Box {
  T value;
  void bad() { value.frobnicate(); }
};

template struct Box<int>;
```

A. Well-formed: `bad` is never called
B. Ill-formed: the explicit instantiation instantiates `bad`, and `int` has no member `frobnicate`
C. Ill-formed, no diagnostic required
D. Well-formed, but calling `Box<int>::bad` anywhere would fail to link

**Answer (B):** Ill-formed: the explicit instantiation instantiates `bad`, and `int` has no member `frobnicate`

**Why:** An explicit instantiation definition of a class template specialization is also an explicit instantiation definition of every member defined at that point, so the body of `bad` is instantiated with `T = int` and fails. Implicit instantiation is the lazy one; explicit instantiation deliberately is not, which is why it is unsuitable for arguments that support only some members. GCC and Clang reject this translation unit.

### Question 6 [tricky] ([temp.point])

According to the C++23 standard, what is the status of this program?

```cpp
namespace n {
  struct A {};
  int score(const A&) { return 1; }
}
template<class T> int pick(T t) { return score(t); }

int first = pick(n::A{});

namespace n { int score(A&) { return 2; } }

int main() { return first; }
```

A. Well-formed; `main` returns 1, because only `score(const A&)` is visible where `pick` is called
B. Well-formed; `main` returns 2, because instantiation happens at the end of the file
C. Ill-formed, no diagnostic required
D. Ill-formed: `score` is not declared when `pick` is defined

**Answer (C):** Ill-formed, no diagnostic required

**Why:** `pick<n::A>` has a point of instantiation right after the declaration of `first`, and the end of the translation unit is also a point of instantiation. At the first, argument-dependent lookup finds only `score(const A&)`; at the second it also finds `score(A&)`, a better match for the lvalue `t`. Two points of instantiation that give different meanings make the program ill-formed, no diagnostic required. GCC 16 and Clang 21 both return 2, which is why the second option is tempting, but that is what the implementations happen to do, not a guarantee.

### Question 7 [standardese] ([temp.expl.spec])

What does the C++23 standard say about this translation unit?

```cpp
template<class T> struct Traits { static constexpr int id = 0; };

int f() { return Traits<int>::id; }

template<> struct Traits<int> { static constexpr int id = 1; };
```

A. Well-formed; `f` returns 0
B. Well-formed; `f` returns 1, since the specialization is found at the end of the file
C. Undefined behavior when `f` is called
D. Ill-formed, no diagnostic required, because the specialization is declared after a use that instantiates `Traits<int>`

**Answer (D):** Ill-formed, no diagnostic required, because the specialization is declared after a use that instantiates `Traits<int>`

**Why:** An explicit specialization must be declared before the first use that would cause an implicit instantiation, in every translation unit with such a use; otherwise the program is ill-formed and no diagnostic is required. Here `Traits<int>::id` instantiates the primary template first. GCC and Clang do diagnose this case within one file, with "specialization of 'Traits<int>' after instantiation", but the standard does not require it, and across translation units the same mistake goes unnoticed.

### Question 8 [standardese] ([temp.explicit])

Several translation units include this header and call `Widget<int>{}.run()`. No translation unit contains `template struct Widget<int>;`. What does the standard say?

```cpp
// widget.h
template<class T> struct Widget { int run(); };
template<class T> int Widget<T>::run() { return 7; }

extern template struct Widget<int>;
```

A. Well-formed: `extern template` is only a hint, and each translation unit may still instantiate `run`
B. Ill-formed, no diagnostic required; in practice a link error for `Widget<int>::run()`
C. Ill-formed: the compiler must diagnose the missing explicit instantiation definition
D. Well-formed: one of the translation units is chosen to instantiate `run`

**Answer (B):** Ill-formed, no diagnostic required; in practice a link error for `Widget<int>::run()`

**Why:** An explicit instantiation declaration suppresses implicit instantiation of the definitions of non-inline members such as `run`. If an entity named by an explicit instantiation declaration is used in a way that would otherwise instantiate it, an explicit instantiation definition must appear somewhere in the program, or the program is ill-formed with no diagnostic required. With GCC 16 this program fails to link with an undefined `Widget<int>::run()`. The hint reading is true only for inline functions, which `run` is not, because it is defined outside the class without `inline`.

# Template argument deduction

> Deduction matches each function parameter type against the type of its argument, independently, and then insists the answers agree. A handful of adjustments, a list of contexts that deduce nothing, and the rule that deduction never considers conversions explain almost every surprising call.

- **Source:** C++ Atlas (https://cppatlas.com/topics/template-argument-deduction)
- **Track:** Templates
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [temp.deduct] (https://eel.is/c++draft/temp.deduct), [temp.deduct.call] (https://eel.is/c++draft/temp.deduct.call), [temp.deduct.type] (https://eel.is/c++draft/temp.deduct.type), [temp.deduct.funcaddr] (https://eel.is/c++draft/temp.deduct.funcaddr), [temp.deduct.conv] (https://eel.is/c++draft/temp.deduct.conv), [temp.arg.explicit] (https://eel.is/c++draft/temp.arg.explicit), [temp.over] (https://eel.is/c++draft/temp.over)
- **cppreference links:** [Template argument deduction](https://en.cppreference.com/w/cpp/language/template_argument_deduction), [Function template](https://en.cppreference.com/w/cpp/language/function_template), [std::type_identity](https://en.cppreference.com/w/cpp/types/type_identity), [Address of an overloaded function](https://en.cppreference.com/w/cpp/language/overloaded_address)
- **Prerequisites:** template-instantiation-and-specialization, value-categories, overload-resolution

## The one idea

When you call a function template without spelling out its arguments, the compiler has to invent them. It does so by pattern matching. Each function parameter whose type mentions a template parameter is a pattern, called `P` in the standard. The type of the corresponding argument, called `A`, is the thing being matched. For every `P`/`A` pair, deduction asks which template arguments would make `P` identical to `A`, after a few adjustments. The pairs are matched independently, and every pair that deduces a given parameter must produce the same answer.

Deduction does not consider implicit conversions. Conversions happen later, in overload resolution, for parameters that did not take part in deduction. Once you hold on to "independent pairs, exact match, then agree", most deduction puzzles solve themselves.

```cpp
template<class T> T biggest(T a, T b) { return a < b ? b : a; }

auto x = biggest(1, 2);           // T = int from both pairs
// auto y = biggest(1, 2.0);      // error: T deduced as int and as double
auto z = biggest<double>(1, 2.0); // T given explicitly; 1 converts to double
```

> **Mental model.** Deduction is pattern matching per parameter, not overload resolution. It never asks "could this convert?", only "what would make these types the same?".

## Adjusting P and A for a call

Before matching, [temp.deduct.call] adjusts both sides so that the pattern resembles how the argument will actually be passed.

If `P` is not a reference type, the argument is going to be copied, so `A` decays. An array type becomes a pointer, a function type becomes a function pointer, and top-level cv-qualifiers on `A` are dropped. Top-level cv-qualifiers on `P` are ignored too. If `P` is a reference type, the type it refers to is used as `P` and `A` is left alone, so arrays and `const` survive.

The third case is the **forwarding reference**: `P` is `T&&` for a template parameter `T` of the function template, with no cv-qualifiers. If the argument is an lvalue, `A` is replaced by "lvalue reference to `A`", so `T` itself becomes a reference type, and reference collapsing turns the parameter into an lvalue reference. The forwarding machinery built on this is covered in the topic on forwarding references and perfect forwarding.

```cpp
template<class T> void byval(T);
template<class T> void byref(T&);
template<class T> void byfwd(T&&);

const int ci = 0;
int arr[3];
void fn(int);

void demo() {
  byval(ci);    // T = int: top-level const dropped
  byval(arr);   // T = int*: array decays
  byval(fn);    // T = void(*)(int): function decays
  byref(ci);    // T = const int: the reference keeps const
  byref(arr);   // T = int[3]: no decay through a reference
  byfwd(ci);    // T = const int&: lvalue argument
  byfwd(0);     // T = int: rvalue argument
}
```

After adjustment, deduction looks for an exact match, with three permitted differences. The deduced `A` may be more cv-qualified than the argument when `P` is a reference, so `const T&` accepts an `int` lvalue with `T = int`. A pointer argument may differ by a qualification conversion, so `const T*` accepts `int*`. And if `P` is a class template specialization such as `Base<T>`, or a pointer to one, the argument may be a class derived from some specialization of `Base`.

```cpp
template<class T> struct Base {};
struct Derived : Base<int> {};
template<class T> void take(Base<T>*);

template<class T> struct Wrapper { Wrapper(T) {} };
template<class T> void wrap(Wrapper<T>);

void demo2() {
  Derived d;
  take(&d);     // OK: T = int, derived-to-base is allowed during deduction
  // wrap(1);   // error: deduction cannot see through the converting constructor
}
```

> **Pitfall.** Writing a template parameter as `Wrapper<T>` and hoping callers pass a `T` never works. The pattern `Wrapper<T>` cannot match `int`, and the converting constructor is invisible to deduction. Either make the parameter deducible from the argument, or supply `T` explicitly.

## Non-deduced contexts

Some parts of a type are positions from which deduction refuses to learn anything. The main ones are:

- anything to the left of `::` in a qualified name, as in `typename Id<T>::type`;
- the operand of `decltype`;
- a non-type template argument or array bound that is an expression involving a template parameter, such as `A<N + 1>`;
- a parameter whose argument is a braced list, unless the parameter is `std::initializer_list<P>` or an array;
- a parameter whose argument is an overload set that matches more than one way, or that contains a function template;
- a parameter used only in a default argument that the call relies on.

A template parameter appearing only in non-deduced contexts must come from somewhere else: another parameter, an explicit argument, or a default. A non-deduced function parameter whose type contains no remaining undeduced parameters is just an ordinary parameter, and ordinary implicit conversions apply to it.

That makes a non-deduced context a tool. C++20's `std::type_identity_t<T>` is exactly `typename std::type_identity<T>::type`, a nested name that blocks deduction, so one parameter decides `T` and the other converts.

```cpp
#include <type_traits>
#include <vector>

template<class T> void scale(std::vector<T>&, std::type_identity_t<T>) {}
template<class T> void scale_bad(std::vector<T>&, T) {}

void demo3() {
  std::vector<double> v;
  scale(v, 2);       // OK: T = double from v; 2 converts to double
  // scale_bad(v, 2); // error: T deduced as double and as int
}
```

> **Standardese.** [temp.deduct.type] lists the non-deduced contexts and says that template parameters appearing in them are not deduced there. A parameter used only in non-deduced contexts, and not given explicitly, makes deduction fail; values deduced from other parameters are substituted into those positions afterwards.

## Braced lists, function addresses and conversion functions

A braced list has no type, so `template<class T> void f(T); f({1, 2});` cannot deduce `T`. Two parameter forms are special-cased. For `std::initializer_list<T>`, each element is deduced against `T` separately. For a reference to an array, `const T(&)[N]`, both the element type and the bound are deduced, which is how a function can learn the length of a braced list.

```cpp
#include <cstddef>
#include <initializer_list>

template<class T> void list(std::initializer_list<T>);
template<class T, std::size_t N> constexpr std::size_t len(const T (&)[N]) { return N; }

void demo4() {
  list({1, 2, 3});              // T = int
  static_assert(len({1, 2, 3, 4}) == 4);  // T = int, N = 4
}
```

Deduction also runs outside calls. Taking the address of a function template where a target type is known deduces from that type, as in `int (*pf)(int) = twice;`, which picks `twice<int>`. Passing an overload set as an argument triggers trial deduction against each member. If exactly one succeeds it is used, and if several succeed the parameter becomes a non-deduced context. A conversion function template, `template<class T> operator T()`, deduces `T` from the type the conversion is needed for, after stripping a reference and top-level cv-qualifiers from it.

```cpp
struct Zero {
  template<class T> operator T() const { return T(); }
};

int i = Zero{};         // T = int
double d = Zero{};      // T = double
bool b = bool(Zero{});  // T = bool
```

## Explicit arguments and default template arguments

Explicit template arguments fill the template parameters from the left, and deduction handles the rest. A function parameter whose type no longer contains any undeduced parameter does not participate in deduction, so implicit conversions are allowed on it. This is why `biggest<double>(1, 2.0)` compiles: both parameters are now just `double`.

Order the template parameters so that the ones callers must spell come first, as in `template<class To, class From> To convert(From)`, called as `convert<double>(1)`.

Since C++11, function templates may have default template arguments. A default is used only when a parameter is neither given explicitly nor deduced. Deduction wins whenever it succeeds.

```cpp
#include <type_traits>

template<class T = double>
const char* kind(T = {}) {
  return std::is_same_v<T, int> ? "int" : std::is_same_v<T, double> ? "double" : "other";
}
// kind(1)        -> "int": deduced from the argument, default ignored
// kind()         -> "double": nothing to deduce from, so the default applies
// kind<long>(1)  -> "other": explicit argument, 1 converts to long
```

Note that `kind()` relies on the default *function* argument `= {}`. A parameter that only appears in a default argument is a non-deduced context, so the default *template* argument is what makes the call work.

## Failure versus hard error, and the two relatives

After deduction, the compiler substitutes the deduced arguments into the function type. If the result is invalid, for example because it names `T::size_type` for `T = int`, that is a deduction failure. The template quietly drops out of overload resolution, which is the rule known as SFINAE, covered in its own topic. Only errors in the *immediate context* of the function type count. An error found while instantiating something else, such as a function body needed to deduce an `auto` return type, is a hard error.

```cpp
template<class T> auto size_a(const T& c) -> decltype(c.size()) { return c.size(); }
int size_a(...) { return -1; }

template<class T> auto size_b(const T& c) { return c.size(); }
int size_b(...) { return -1; }

int ok = size_a(42);      // -1: substitution into the return type fails, template removed
// int no = size_b(42);   // hard error: the body is instantiated to deduce the return type
```

Two neighbouring features reuse this machinery. A variable declared with `auto` is deduced as if `auto` were a template parameter `T` and the initializer an argument for a parameter of type `T`, with one notable difference: `auto x = {1, 2};` deduces `std::initializer_list<int>`, where a template would fail. The details live in the topic on `auto` and `decltype`. Class template argument deduction, since C++17, deduces a class template's arguments by running this same deduction against a set of invented function templates made from constructors and deduction guides; it has its own topic.

## What to remember

- Each `P`/`A` pair is matched independently; all deductions of a parameter must agree, and no implicit conversions are considered.
- By-value parameters decay the argument and drop its top-level cv; reference parameters keep arrays and `const`.
- `T&&` with an lvalue argument deduces `T` as an lvalue reference.
- Allowed differences are extra cv through a reference, qualification conversions on pointers, and derived-to-base for class template specializations.
- Nested names, `decltype`, expressions in template arguments, and braced lists are non-deduced; `std::type_identity_t` uses this on purpose.
- Braced lists deduce only into `std::initializer_list<T>` or a reference to an array.
- Explicit arguments fill from the left; parameters left with nothing to deduce accept conversions.
- Defaults apply only when nothing was deduced or given; substitution failures in the immediate context remove the candidate, while errors in bodies are hard errors.

## Concept Map Outline

- **Template argument deduction:** Match each parameter type P against its argument type A, independently, then require agreement.
  - **P/A adjustments:** Both sides are adjusted to reflect how the argument is passed.
    - **By value:** Arrays and functions decay to pointers; top-level cv on A is dropped.
    - **By reference:** The referred-to type is matched; arrays and const survive.
    - **Forwarding reference:** T&& with an lvalue deduces T as an lvalue reference.
  - **Exact match rules:** Deduction never considers implicit conversions.
    - **Conflicts fail:** biggest(1, 2.5) deduces int and double for T, so deduction fails.
    - **Allowed differences:** Extra cv through references, qualification conversions, and derived-to-base.
    - **No user conversions:** Wrapper<T> cannot be deduced from an int through a converting constructor.
  - **Non-deduced contexts:** Positions from which deduction learns nothing.
    - **Nested names:** Anything left of :: such as typename Id<T>::type.
    - **Expressions:** decltype operands and template arguments like A<N + 1>.
    - **type_identity_t:** Blocks deduction on purpose so that parameter accepts conversions.
  - **Other sources:** Deduction also runs outside ordinary typed arguments.
    - **Braced lists:** Deduce only into std::initializer_list<T> or a reference to an array.
    - **Function addresses:** A target function pointer type deduces the template's arguments.
    - **Overload set arguments:** Trial deduction per member; more than one success makes it non-deduced.
    - **Conversion templates:** operator T() deduces T from the required type, reference and cv stripped.
  - **Explicit and default:** Arguments not deduced must come from somewhere.
    - **Explicit from left:** Given arguments fill leading parameters; fully specified parameters convert.
    - **Defaults last resort:** A default template argument is used only if nothing was deduced or given.
  - **After deduction:** Substitution and the relatives that reuse the rules.
    - **Deduction failure:** Invalid types in the immediate context drop the candidate: SFINAE.
    - **Hard errors:** Errors in instantiated bodies, such as for auto return types, are not SFINAE.
    - **auto and CTAD:** auto deduces like a template parameter; CTAD deduces from constructors and guides.

## Standardese Quiz Questions

### Question 1 [warmup] ([temp.deduct.call], [temp.deduct.type])

Is this program well-formed, and if so what does it return?

```cpp
template<class T> T biggest(T a, T b) { return a < b ? b : a; }

int main() {
  return static_cast<int>(biggest(1, 2.5));
}
```

A. Well-formed; returns 2, because `T` is deduced as `double`
B. Well-formed; returns 1, because `T` is deduced from the first argument as `int`
C. Ill-formed: `T` is deduced as `int` from one argument and as `double` from the other
D. Ill-formed: the call is ambiguous between `biggest<int>` and `biggest<double>`

**Answer (C):** Ill-formed: `T` is deduced as `int` from one argument and as `double` from the other

**Why:** Each parameter/argument pair is deduced independently: the first gives `T = int`, the second `T = double`, and conflicting deductions make deduction fail, so there is no viable function. Deduction never considers the usual arithmetic conversions, so the "common type" answer is the tempting wrong one. `biggest<double>(1, 2.5)` would compile, because explicitly specified parameters no longer take part in deduction and `1` then converts.

### Question 2 [warmup] ([temp.deduct.call], [expr.type])

What is `T` deduced as?

```cpp
template<class T> void f(T x);

void g(const int& r) {
  f(r);
}
```

A. `const int&`
B. `const int`
C. `int&`
D. `int`

**Answer (D):** `int`

**Why:** The expression `r` has type `const int`; references are stripped from an expression's type before anything else happens. Because `P` is the non-reference `T`, top-level cv-qualifiers of `A` are dropped as well, so `T = int` and the parameter is a fresh copy. `const int&` is tempting if you think of deduction as copying the declared type of the variable, which it does not.

### Question 3 [warmup] ([temp.deduct.call], [dcl.ref])

What is `T` deduced as in the call `g(i)`?

```cpp
template<class T> void g(T&& x);

void h() {
  int i = 0;
  g(i);
}
```

A. `int`
B. `int&`
C. `int&&`
D. Nothing: an lvalue cannot bind to `T&&`, so the call is ill-formed

**Answer (B):** `int&`

**Why:** `T&&` where `T` is a function template parameter is a forwarding reference. For an lvalue argument, deduction uses "lvalue reference to `A`" in place of `A`, giving `T = int&`, and reference collapsing turns `int& &&` into `int&`. With `T = int` the parameter would be `int&&`, which cannot bind an lvalue; that rule is what the last option misremembers.

### Question 4 [tricky] ([temp.deduct.type], [temp.arg.explicit])

Which of the two calls in `demo` is well-formed?

```cpp
#include <type_traits>
#include <vector>

template<class T> void scale_a(std::vector<T>&, T) {}
template<class T> void scale_b(std::vector<T>&, std::type_identity_t<T>) {}

void demo() {
  std::vector<double> v;
  scale_a(v, 2);  // #1
  scale_b(v, 2);  // #2
}
```

A. Both: `2` converts to `double` in each case
B. Neither: `T` conflicts in both
C. Only #2
D. Only #1

**Answer (C):** Only #2

**Why:** In `scale_a`, the second parameter deduces `T = int`, which conflicts with `T = double` from the vector, so deduction fails and #1 is ill-formed. In `scale_b`, `std::type_identity_t<T>` is the nested name `std::type_identity<T>::type`, a non-deduced context, so `T = double` comes only from the vector and `2` is then converted like an ordinary argument. Conversions are never considered during deduction, which is why the first option is wrong.

### Question 5 [tricky] ([temp.deduct.call], [dcl.type.auto.deduct])

Is the call `f({1, 2, 3})` well-formed?

```cpp
#include <initializer_list>

template<class T> void f(T) {}

int main() {
  auto il = {1, 2, 3};
  f(il);
  f({1, 2, 3});
}
```

A. Yes: `T` is deduced as `std::initializer_list<int>`, just as for `il`
B. No: a braced list makes the parameter a non-deduced context, so `T` cannot be deduced
C. Yes: `T` is deduced as `int[3]`
D. Yes: `T` is deduced as `int`, from the first element

**Answer (B):** No: a braced list makes the parameter a non-deduced context, so `T` cannot be deduced

**Why:** A braced-init-list has no type. Unless the parameter is `std::initializer_list<P>` or a reference to an array, an initializer-list argument makes the parameter a non-deduced context, and `T` is left undeduced, so the call is ill-formed. The tempting answer comes from `auto`: `auto il = {1, 2, 3};` deduces `std::initializer_list<int>` by a special rule for `auto`, and `f(il)` then deduces from an ordinary expression.

### Question 6 [tricky] ([temp.deduct.type], [temp.deduct])

What does this program print?

```cpp
#include <cstdio>
#include <type_traits>

template<class T = double>
const char* kind(T = {}) {
  return std::is_same_v<T, int> ? "int" : std::is_same_v<T, double> ? "double" : "other";
}

int main() {
  std::puts(kind(1));
  std::puts(kind());
}
```

A. `double`, `double`
B. `int`, `double`
C. `int`, then a compile error for `kind()`
D. `double`, then `other`

**Answer (B):** `int`, `double`

**Why:** A default template argument is used only when the parameter is neither specified nor deduced. In `kind(1)`, `T` is deduced as `int` from the argument, so the default is ignored. In `kind()`, the only function parameter relies on its default argument, which is a non-deduced context, so `T` falls back to `double` and `{}` value-initializes it. Without the default template argument, `kind()` would be the compile error of the third option.

### Question 7 [standardese] ([temp.deduct.type])

In which of these function parameter types is `T` in a non-deduced context, so that a call `f(x)` can never deduce `T`?

A. `const T&`
B. `std::vector<T>*`
C. `typename std::remove_reference<T>::type&`
D. `T (*)(int)`
E. `T[4]` passed by reference, as `T (&)[4]`

**Answer (C):** `typename std::remove_reference<T>::type&`

**Why:** The nested-name-specifier of a qualified type name is a non-deduced context: the compiler would have to invert an arbitrary metafunction, which it cannot. This is why `std::forward<T>` takes `typename std::remove_reference<T>::type&` and must be called with an explicit `T`. The other forms are all built from `T` with compound type constructors (references, pointers, template-ids, function types and arrays), and all of them can be deduced from a matching argument type.

### Question 8 [standardese] ([temp.deduct.call])

Which of the calls in `demo` are well-formed?

```cpp
template<class T> struct Base {};
struct Derived : Base<int> {};
template<class T> void take(Base<T>*) {}

template<class T> struct Wrapper { Wrapper(T) {} };
template<class T> void wrap(Wrapper<T>) {}

void demo() {
  Derived d;
  take(&d);  // #1
  wrap(1);   // #2
}
```

A. Both
B. Only #1
C. Only #2
D. Neither

**Answer (B):** Only #1

**Why:** [temp.deduct.call] lists the only differences allowed between the adjusted parameter and argument types; one is that when `P` is a class template specialization or a pointer to one, `A` may be a derived class, so #1 deduces `T = int` from the base `Base<int>`. User-defined conversions are not on the list: `Wrapper<T>` cannot match `int`, and the converting constructor is invisible to deduction, so #2 is ill-formed. A non-template `void wrap(Wrapper<int>)` would accept `1`, which is why #2 looks plausible.

# Dependent names and two-phase lookup

> A template is checked twice, once when it is defined and once for each set of arguments. Names that do not depend on the template parameters are bound at the definition, dependent names wait for instantiation, and the parser needs `typename` and `template` to read dependent code before it knows what the names mean.

- **Source:** C++ Atlas (https://cppatlas.com/topics/dependent-names-and-two-phase-lookup)
- **Track:** Templates
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [temp.res] (https://eel.is/c++draft/temp.res), [temp.res.general] (https://eel.is/c++draft/temp.res.general), [temp.dep] (https://eel.is/c++draft/temp.dep), [temp.dep.type] (https://eel.is/c++draft/temp.dep.type), [temp.dep.expr] (https://eel.is/c++draft/temp.dep.expr), [temp.dep.res] (https://eel.is/c++draft/temp.dep.res), [temp.dep.candidate] (https://eel.is/c++draft/temp.dep.candidate), [basic.lookup.argdep] (https://eel.is/c++draft/basic.lookup.argdep)
- **cppreference links:** [Dependent names](https://en.cppreference.com/w/cpp/language/dependent_name), [Argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl), [Injected-class-name](https://en.cppreference.com/w/cpp/language/injected-class-name)
- **Prerequisites:** name-lookup-and-adl, template-instantiation-and-specialization

## The one idea

The compiler reads a template definition before it knows the template arguments. Anything in it that does not depend on the template parameters can be checked and resolved immediately, and is. Anything that does depend on them, such as `t.size()` for a parameter `t` of type `T`, can only be resolved when the template is instantiated for a specific `T`. This is **two-phase lookup**: phase one happens at the definition, phase two at each point of instantiation.

Three practical consequences follow. A non-dependent name is bound to whatever is visible at the definition, and later declarations cannot change it. A dependent function call can still find functions declared after the template, but only through argument-dependent lookup. And because the parser must build a syntax tree in phase one, it needs to be told when a dependent name is a type or a template.

> **Mental model.** Phase one asks "what does this mean for every `T`?" and resolves what it can. Phase two fills in the holes for one particular `T`, using argument-dependent lookup as the only window onto declarations that came later.

## What depends on a template parameter

[temp.dep] defines dependency structurally. A **dependent type** is a template parameter, or a type built from one: `T*`, `const T&`, `std::vector<T>`, `T::value_type`, `decltype(t)` where `t` has a dependent type, and so on. An expression is **type-dependent** if its type depends on a template parameter, as `t` and `t + 1` do, and **value-dependent** if its value does, as `sizeof(T)` and a non-type parameter `N` do.

A function call with an unqualified name, such as `f(t)`, is a **dependent call** when any argument is type-dependent. Then the name `f` itself is dependent and is resolved in phase two. A call with no dependent arguments, like `f(1)`, is not dependent, even inside a template.

```cpp
#include <cstdio>

void g(double) { std::puts("g(double)"); }

template<class T> void call(T) { g(1); }  // not dependent: bound to g(double) here

void g(int) { std::puts("g(int)"); }      // too late for call<T>

int main() { call(0); }                    // prints g(double)
```

## Phase one: checked at the definition

In phase one, compilers check syntax, look up every non-dependent name, and diagnose errors in constructs that do not depend on any parameter. GCC and Clang both reject an unqualified call to an undeclared function with no dependent arguments, even in a template that is never instantiated.

```cpp
template<class T> void s() {
  // undeclared();  // error: no arguments depend on T, so a declaration must be visible
}
```

The standard is more permissive about other errors. If no valid specialization of a template could ever be generated, or if a construct that does not depend on a parameter would be ill-formed in a hypothetical instantiation right after the definition, the program is ill-formed with no diagnostic required. Compilers differ in how far they go: Clang 21 rejects `int i = "text";` inside an uninstantiated function template, while GCC 16 says nothing until it instantiates.

> **Standardese.** [temp.res.general] says a program is ill-formed, no diagnostic required, if no valid specialization can be generated for a template, or if a hypothetical instantiation immediately after the definition would be ill-formed because of a construct that does not depend on a template parameter. That is the licence for early diagnosis, not an obligation.

## Phase two: dependent calls and ADL

For a dependent unqualified call, [temp.dep.candidate] combines two lookups. Ordinary unqualified lookup is done only from the template definition context. Argument-dependent lookup is done from both the definition context and the instantiation context. So functions declared after the template are found only if they live in a namespace associated with an argument's type.

```cpp
template<class T> int twice(T t) { return helper(t) * 2; }

namespace lib {
  struct X {};
  int helper(X) { return 21; }   // found by ADL at the point of instantiation
}
int helper(int) { return 1; }    // declared after twice, in the global namespace

int a = twice(lib::X{});         // 42
// int b = twice(0);             // error: int has no associated namespaces,
//                               // and ordinary lookup only saw the definition context
```

That asymmetry is why customization points are found by argument-dependent lookup. A generic algorithm can call `swap(a, b)` unqualified after `using std::swap;`, and the user's `swap` in the user's namespace is found at instantiation even though the algorithm's header was included first. It also explains why such customization does not work for fundamental types: `int` has no associated namespaces, so nothing declared later can be found for it. The general rules of argument-dependent lookup are in the topic on name lookup and ADL.

## `typename` and `template`: telling the parser

In phase one, the compiler does not know whether `T::value_type` names a type, a static data member, or a member template. It assumes a qualified dependent name is not a type unless you say `typename`, and not a template unless you say `template`. The assumption is enforced: without the keyword, the code is parsed as an expression.

```cpp
template<class T> void q() {
  // T::type * ptr;          // parsed as T::type multiplied by ptr, so ptr must exist
  typename T::type* ptr2 = nullptr;  // declares a pointer
  (void)ptr2;
}

template<class T> struct H { template<int N> int get() const { return N; } };

template<class T> int use(const H<T>& h) {
  // return h.get<3>();      // error: parsed as (h.get < 3) > ()
  return h.template get<3>();  // OK: get is a member template
}
```

The same applies to `T::template rebind<U>` and `p->template f<int>()`. The `template` keyword is needed only after `.`, `->` or `::` when the left-hand side is dependent and the name is followed by `<`.

C++20 adopted P0634, which drops the `typename` requirement in contexts where only a type can appear. These include alias declarations, the types of class members and member function returns and parameters, return types and trailing return types of function declarations at namespace scope, the target type of a named cast, and the type in a `new` expression. Inside a function body, where a statement could equally be an expression, `typename` is still required.

```cpp
#include <vector>

template<class T> struct S {
  using V = T::value_type;            // OK since C++20
  T::value_type member;               // OK since C++20
  T::value_type get() const { return member; }  // OK since C++20
  void f() {
    typename T::value_type local{};   // still required in a block
    (void)local;
  }
};
template<class T> T::value_type first(const T& c) { return c[0]; }  // OK since C++20
```

> **Pitfall.** A parameter of a namespace-scope function declaration is not a type-only context unless the declarator is qualified. `template<class T> void p(T::type);` is read as a variable `p` of type `void`, initialized with `T::type`, and rejected. Write `typename` there.

Since C++20, P0846 also lets an unqualified name followed by `<` be treated as a template name when ordinary lookup finds nothing or finds only functions, so `get<0>(t)` finds `std::get` through argument-dependent lookup without a `using` declaration.

## Dependent bases and the current instantiation

Inside a class template, some names are known in phase one even though they are technically dependent. The **current instantiation** is the class being defined: inside `template<class T> struct Node`, the names `Node`, `Node<T>` and `this` all refer to it. Members of the current instantiation are looked up at definition time, so `Node<T>::value_type` needs no `typename` if `value_type` is declared in `Node`, and `this->nope` for a member that does not exist can be diagnosed immediately when the class has no dependent bases.

A base class that depends on a parameter, such as `Base<T>`, is different. It is an **unknown specialization**: someone could explicitly specialize `Base<int>` with completely different members. So unqualified lookup in phase one does not look into dependent bases at all, and an unqualified name used in a derived class template is not found there.

```cpp
template<class T> struct Base { int size() const { return 1; } };

int size() { return 0; }  // an unrelated global function

template<class T> struct Derived : Base<T> {
  int a() const { return this->size(); }    // 1: dependent, found in Base<T> later
  int b() const { return size(); }          // 0: non-dependent, binds to ::size now
  int c() const { return Base<T>::size(); } // 1: qualified (would also suppress virtual dispatch)
};
```

Writing `this->`, qualifying with `Base<T>::`, or adding `using Base<T>::size;` all make the name dependent so it is looked up in phase two. Without a global `size`, `b()` would be a phase-one error: GCC says there are no arguments to `size` that depend on a template parameter. With one, it silently calls the wrong function, which is the nastiest form of this bug. The two disambiguation problems also combine: calling a member template of a dependent base needs both fixes at once, as in `this->template get<0>()`, because `this->get<0>()` would again parse the `<` as less-than. GCC's `-fpermissive` flag turns some of these phase-one errors into warnings, which helps when porting old code but only hides the problem.

> **Pitfall.** Code written for older MSVC versions often relied on finding names in dependent bases without `this->`, because that compiler did not implement two-phase lookup until its `/permissive-` mode. Such code fails on GCC and Clang, or, as above, quietly calls something else.

## What to remember

- Non-dependent names are looked up and bound at the template definition; later declarations do not affect them.
- A call is dependent when an argument is type-dependent; then ordinary lookup uses the definition context and ADL adds the instantiation context.
- Functions declared after a template are found only by ADL, so they are never found for fundamental types.
- A qualified dependent name is assumed to be a value unless marked `typename`, and not a template unless marked `template`.
- C++20 makes `typename` optional where only a type can appear, but not in function bodies or unqualified namespace-scope function parameters.
- Dependent base classes are not searched by unqualified lookup; use `this->`, `Base<T>::` or a using-declaration.
- A template that can never be validly instantiated is ill-formed, no diagnostic required; how early compilers complain varies.

## Concept Map Outline

- **Two-phase lookup:** Non-dependent names resolve at the definition; dependent names resolve at instantiation.
  - **What is dependent:** Dependency is defined structurally from the template parameters.
    - **Dependent types:** T, T*, vector<T>, T::type and decltype of a type-dependent expression.
    - **Dependent expressions:** Type-dependent like t + 1, or value-dependent like sizeof(T) or N.
    - **Dependent calls:** An unqualified call is dependent when any argument is type-dependent.
  - **Phase one:** Checked when the template definition is parsed.
    - **Bound at definition:** Non-dependent names bind to what is visible there; later overloads are ignored.
    - **Early errors:** An undeclared non-dependent function call is rejected even if never instantiated.
    - **Never valid: IFNDR:** No valid specialization possible: ill-formed NDR; Clang diagnoses more than GCC.
  - **Phase two:** Dependent names are resolved for each specialization.
    - **Ordinary lookup:** For dependent calls, only from the template definition context.
    - **ADL both contexts:** Argument-dependent lookup also searches from the point of instantiation.
    - **Fundamental types:** int has no associated namespaces, so later declarations are never found.
  - **Disambiguators:** Tell the parser what a dependent qualified name is.
    - **typename:** Without it, T::type is assumed to be a value; T::type * p is multiplication.
    - **template keyword:** Needed in h.template get<3>() when h is dependent and < follows.
    - **C++20 P0634:** typename optional in type-only contexts such as aliases, members and returns.
    - **Still required:** In function bodies and unqualified namespace-scope function parameters.
  - **Class templates:** Which members are known while the class is being defined.
    - **Current instantiation:** Node, Node<T> and this name it; its members are looked up in phase one.
    - **Dependent bases:** Unknown specializations; unqualified lookup never searches them.
    - **this-> fix:** this->, Base<T>:: or a using-declaration defers the name to phase two.
    - **Silent global:** An unqualified call may bind to a global function instead of the base member.

## Standardese Quiz Questions

### Question 1 [warmup] ([temp.dep], [temp.res])

Is this program well-formed?

```cpp
template<class T> struct Base { void hello() {} };

template<class T> struct Derived : Base<T> {
  void run() { hello(); }
};

int main() { Derived<int>{}.run(); }
```

A. Well-formed: `hello` is found in `Base<int>` when `Derived<int>` is instantiated
B. Ill-formed: `hello` is not found, because unqualified lookup does not search the dependent base `Base<T>`
C. Ill-formed, no diagnostic required
D. Well-formed only because `Base<int>` is not explicitly specialized

**Answer (B):** Ill-formed: `hello` is not found, because unqualified lookup does not search the dependent base `Base<T>`

**Why:** `hello()` has no arguments, so it is not a dependent call and is looked up in phase one. Unqualified lookup at the definition does not look into `Base<T>`, a dependent base, because a specialization of `Base` could have entirely different members. Nothing named `hello` is visible, so the program is ill-formed and GCC and Clang both reject it. Writing `this->hello()` or `Base<T>::hello()` makes the name dependent and fixes it.

### Question 2 [warmup] ([temp.names], [temp.res])

`use` fails to compile because `h.get<3>()` is parsed as comparisons. What is the correct spelling of the return expression?

```cpp
template<class T> struct H { template<int N> int get() const { return N; } };

template<class T> int use(const H<T>& h) {
  return h.get<3>();
}

int x = use(H<int>{});
```

A. `return typename h.get<3>();`
B. `return h.template get<3>();`
C. `return h.get template<3>();`
D. No change: since C++20 the compiler looks inside `H<T>` to see that `get` is a template

**Answer (B):** `return h.template get<3>();`

**Why:** `h` has a dependent type, so in phase one the compiler cannot know that `get` is a member template, and without help the `<` is a less-than operator; the original code is ill-formed. The `template` keyword after `.` tells the parser that the next name is a template. `typename` marks types, not templates, and C++20 relaxed only `typename` in type-only contexts and the lookup of unqualified template-ids, neither of which helps a member access.

### Question 3 [warmup] ([temp.res], [temp.dep])

What does this program print?

```cpp
#include <cstdio>

void g(double) { std::puts("g(double)"); }

template<class T> void call(T) { g(1); }

void g(int) { std::puts("g(int)"); }

int main() { call(0); }
```

A. `g(int)`
B. Ill-formed: the call `g(1)` is ambiguous
C. `g(double)`
D. It depends on the compiler

**Answer (C):** `g(double)`

**Why:** `g(1)` has no type-dependent arguments, so it is not a dependent call: it is looked up and bound at the template definition, where only `g(double)` is visible. The later `g(int)` would be a better match, which is why `g(int)` is tempting, but it is never considered for this call. If the call were `g(T{})`, it would be dependent, though ordinary lookup would still see only `g(double)`, and argument-dependent lookup finds nothing for `int`.

### Question 4 [tricky] ([temp.dep], [temp.res])

What does this program return?

```cpp
template<class T> struct Base { int size() const { return 1; } };

int size() { return 0; }

template<class T> struct Derived : Base<T> {
  int n() const { return size(); }
};

int main() { return Derived<int>{}.n(); }
```

A. 0
B. 1
C. Ill-formed: the call is ambiguous between `::size` and `Base<int>::size`
D. Ill-formed: `size` is not found in `Base<T>`

**Answer (A):** 0

**Why:** `size()` is not a dependent call, so it is looked up at the definition, and unqualified lookup skips the dependent base `Base<T>`. It finds the global `::size`, binds to it, and `n` returns 0. There is no ambiguity, because `Base<int>::size` is never a candidate. Without the global function, the program would be ill-formed as the last option says; with it, the bug is silent.

### Question 5 [tricky] ([temp.dep.candidate], [basic.lookup.argdep])

Which of the two uses of `twice` are well-formed?

```cpp
template<class T> int twice(T t) { return helper(t) * 2; }

namespace lib {
  struct X {};
  int helper(X) { return 21; }
}
int helper(int) { return 1; }

int a = twice(lib::X{});  // #1
int b = twice(0);         // #2
```

A. Both: `helper` is looked up at the point of instantiation, where both overloads are visible
B. Only #2
C. Neither: `helper` must be declared before the template
D. Only #1

**Answer (D):** Only #1

**Why:** `helper(t)` is a dependent call. Ordinary unqualified lookup is done only from the definition context, where no `helper` exists, and argument-dependent lookup is done from both the definition and instantiation contexts. For `lib::X`, ADL searches `lib` and finds `lib::helper`. For `int`, there are no associated namespaces, so the global `helper(int)` declared after the template is never found and #2 is ill-formed. The first option describes a single lookup at instantiation, which is not the rule.

### Question 6 [tricky] ([temp.res], [temp.res.general])

How does a conforming compiler parse the statement in `q`?

```cpp
template<class T> void q() {
  T::type * ptr;
}
```

A. As a declaration of `ptr`, a pointer to `T::type`
B. As a multiplication of `T::type` by `ptr`, which here is ill-formed because `ptr` is not declared
C. It is deferred until instantiation, when the compiler knows what `T::type` is
D. As a declaration in C++20 and later, because P0634 made `typename` optional

**Answer (B):** As a multiplication of `T::type` by `ptr`, which here is ill-formed because `ptr` is not declared

**Why:** A qualified name that depends on a template parameter is assumed not to name a type unless it is preceded by `typename`, so the statement is an expression: `T::type` times `ptr`. `ptr` is a non-dependent name and is undeclared, so phase one rejects the template. P0634 removed the need for `typename` only in contexts where a type is the only possible parse, and a statement in a function body is not one of them.

### Question 7 [standardese] ([temp.res.general])

In C++23, in which of these positions inside `template<class T> struct S { ... };` is `typename` still required before `T::value_type`?

A. `using V = T::value_type;`
B. `T::value_type member;` as a data member
C. `void set(T::value_type v);` as a member function parameter
D. `void f() { T::value_type local{}; }` inside a member function body
E. `auto g() -> T::value_type;` as a trailing return type

**Answer (D):** `void f() { T::value_type local{}; }` inside a member function body

**Why:** C++20's P0634 defines type-only contexts in which a dependent qualified name is assumed to be a type: alias declarations, the decl-specifiers of member declarations, parameters in member declarations, trailing return types, named cast targets and a few more. A statement in a function body is not such a context, because `T::value_type local{};` could equally be an expression, so `typename` is still required there. All the other positions compile without it in C++20 and later.

### Question 8 [standardese] ([temp.res.general])

The function template `u` is never instantiated. What does the C++23 standard say about this translation unit?

```cpp
template<class T> void u() {
  int i = "text";
  (void)i;
}

int main() {}
```

A. Well-formed: templates are only checked when instantiated
B. Ill-formed, and a diagnostic is required
C. Undefined behavior
D. Ill-formed, no diagnostic required

**Answer (D):** Ill-formed, no diagnostic required

**Why:** The initialization does not depend on `T`, and it would be ill-formed in a hypothetical instantiation right after the definition; no valid specialization of `u` can be generated either. [temp.res.general] makes such a program ill-formed with no diagnostic required. That permits early diagnosis without requiring it: Clang 21 rejects this translation unit, while GCC 16 accepts it, which is why the first option looks right on GCC.

# Variadic templates and fold expressions

> A parameter pack stands for zero or more template or function arguments, and the only thing you can do with one is expand it, repeating a pattern once per element. C++17 fold expressions reduce a pack with an operator, replacing most of the recursion that C++11 variadic code needed.

- **Source:** C++ Atlas (https://cppatlas.com/topics/variadic-templates-and-fold-expressions)
- **Track:** Templates
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [temp.variadic] (https://eel.is/c++draft/temp.variadic), [expr.prim.fold] (https://eel.is/c++draft/expr.prim.fold), [expr.sizeof] (https://eel.is/c++draft/expr.sizeof), [temp.param] (https://eel.is/c++draft/temp.param), [dcl.fct] (https://eel.is/c++draft/dcl.fct), [temp.deduct.call] (https://eel.is/c++draft/temp.deduct.call), [expr.comma] (https://eel.is/c++draft/expr.comma)
- **cppreference links:** [Parameter pack](https://en.cppreference.com/w/cpp/language/parameter_pack), [Fold expressions](https://en.cppreference.com/w/cpp/language/fold), [sizeof... operator](https://en.cppreference.com/w/cpp/language/sizeof...), [std::forward](https://en.cppreference.com/w/cpp/utility/forward)
- **Prerequisites:** template-argument-deduction, forwarding-references-and-perfect-forwarding

## The one idea

A **parameter pack** is a name that stands for a list of zero or more things: types, values, templates, or function parameters. You cannot index it, loop over it, or pass it around as a unit in C++23. The one operation is **pack expansion**: you write a pattern that mentions the pack, follow it with `...`, and the compiler stamps out one copy of the pattern per element, separated by commas. A **fold expression** is a second, C++17 form of expansion that joins the copies with a binary operator instead of commas.

Every rule in this topic is a refinement of that. The pattern decides what gets repeated, the context decides where repetition is allowed, and deduction decides how long the pack is.

> **Mental model.** `pattern...` is a compile-time copy-and-paste. `f(g(xs)...)` becomes `f(g(x1), g(x2), g(x3))`; the `...` applies to the whole pattern to its left, not just to the pack name.

## Four kinds of pack

A template parameter pack is declared with `...` before the name. It can be a type pack (`class... Ts`), a non-type pack (`int... Ns`, or `auto... Vs` since C++17), or a template template pack (`template<class> class... Ts`). A **function parameter pack** is a function parameter whose type contains a template parameter pack, as in `Ts... xs`; its type is itself a pack expansion. C++20 added init-capture packs in lambdas, `[...ys = xs]`.

`sizeof...(pack)` gives the number of elements as a constant expression of type `std::size_t`. It counts elements; it has nothing to do with `sizeof`.

```cpp
#include <tuple>

template<class... Ts> constexpr auto count = sizeof...(Ts);
static_assert(count<int, void, char[3]> == 3);  // void is fine: no object is formed
static_assert(count<> == 0);

template<int... Ns> constexpr int isum = (Ns + ... + 0);
static_assert(isum<1, 2, 3> == 6);

template<template<class> class... Ts> struct Apply {
  using type = std::tuple<Ts<int>...>;  // one specialization per template
};

template<class... Ts> auto capture(Ts... xs) {
  return [...ys = xs] { return (ys + ...); };  // C++20 init-capture pack
}
```

A primary class, variable or alias template may have at most one template parameter pack, and it must come last. Function templates are more relaxed: a pack may be followed by template parameters that can be deduced from the function parameters or that have defaults.

## Patterns and where they can expand

The pattern is everything that belongs to the `...`. It may be as simple as the pack name or an arbitrarily complex expression or type. Moving the `...` changes the meaning completely.

```cpp
int g(int x) { return x * 10; }
template<class... Ts> int f(Ts... xs) { return (0 + ... + xs); }

template<class... Ts> int per_element(Ts... xs) { return f(g(xs)...); }  // f(g(x1), g(x2))
template<class... Ts> int all_at_once(Ts... xs) { return g(f(xs...)); }  // g(f(x1, x2))
```

A pattern may name several packs. They are expanded in lockstep, so they must all have the same length, and the program is ill-formed if they do not.

```cpp
#include <utility>

template<class... Ts> struct List {};
template<class... Ts> struct Zip {
  template<class... Us> using with = List<std::pair<Ts, Us>...>;
};
// Zip<int, char>::with<long, bool> is List<pair<int, long>, pair<char, bool>>
// Zip<int, char>::with<long> is ill-formed: lengths 2 and 1
```

Expansion is allowed only in contexts that are themselves comma-separated lists: function call arguments, template argument lists, braced initializer lists, base class lists, member initializer lists, lambda capture lists, `using` declarations (since C++17), `alignas` and attribute lists, and fold expressions. A bare `xs...;` as a statement is not one of them, and neither is `std::printf("%d", xs);` without any `...`, which is rejected as an unexpanded pack.

```cpp
template<class... Fs> struct overloaded : Fs... {  // pack expansion in the base list
  using Fs::operator()...;                         // C++17 pack expansion in using
};
```

> **Pitfall.** `xs + 1...` does not compile. The preprocessor reads `1...` as a single preprocessing number, which is not a valid token. Write `(xs + 1)...` or put a space before the dots.

## Recursion, then folds

Before C++17, the standard way to process a pack was recursion: peel off the first element, handle it, and recurse on the rest, with a non-variadic overload as the base case. It works, but it instantiates one function per element and spreads the logic over several declarations. The other C++11 idiom was expansion into an array initializer, abusing the comma operator to run an expression per element in a guaranteed order.

```cpp
#include <cstdio>

void print_rec() { std::puts(""); }                        // base case
template<class T, class... Rest> void print_rec(T t, Rest... rest) {
  std::printf("%d", t);
  print_rec(rest...);                                      // one instantiation per length
}

template<class... Ts> void print_array(Ts... xs) {
  int dummy[] = {0, (std::printf("%d", xs), 0)...};        // C++11 trick
  (void)dummy;
}

template<class... Ts> void print_fold(Ts... xs) {
  (std::printf("%d", xs), ...);                            // C++17
}
```

C++17 also allows the recursion to live in one function: `if constexpr (sizeof...(rest) > 0)` guards the recursive call, so no separate base-case overload is needed, but there is still one instantiation per length. A fold does the same work in a single instantiation and a single expression, and it is the default choice whenever the per-element work fits in an expression.

## The four fold forms

A fold expression is always parenthesized and uses one of 32 binary operators. With a pack `E` holding `E1, E2, E3` and an initial value `I`:

| Form | Spelling | Expands to |
| --- | --- | --- |
| Unary right fold | `(E op ...)` | `E1 op (E2 op E3)` |
| Unary left fold | `(... op E)` | `(E1 op E2) op E3` |
| Binary right fold | `(E op ... op I)` | `E1 op (E2 op (E3 op I))` |
| Binary left fold | `(I op ... op E)` | `((I op E1) op E2) op E3` |

The side the dots are on is the side the parentheses pile up on. For associative operators it does not matter; for subtraction or division it decides the answer.

```cpp
template<class... Ts> int rsub(Ts... xs) { return (xs - ...); }  // 10 - (4 - 3) == 9
template<class... Ts> int lsub(Ts... xs) { return (... - xs); }  // (10 - 4) - 3 == 3
```

The operand of a fold must be a cast-expression, so `(xs * 2 + ...)` is ill-formed; write `((xs * 2) + ...)`. The binary forms exist mainly for an initial value and for streams, as in `(std::cout << ... << xs)`.

An empty pack is where the forms differ. A binary fold of an empty pack is just `I`. A unary fold of an empty pack is allowed for exactly three operators: `&&` gives `true`, `||` gives `false`, and the comma operator gives `void()`. Every other operator, including `+` and `*`, makes the instantiation ill-formed, because the identity values in the original proposal were removed before C++17 shipped.

```cpp
template<class... Ts> constexpr bool all(Ts... xs) { return (... && xs); }
template<class... Ts> constexpr auto sum(Ts... xs) { return (xs + ... + 0); }
static_assert(all() && sum() == 0);
// (xs + ...) with an empty pack: error, no fallback value for +
```

> **Standardese.** [temp.variadic] says that when a unary fold is instantiated with an empty pack, `&&` yields `true`, `||` yields `false`, the comma operator yields `void()`, and for any other operator the instantiation is ill-formed.

## Folding over the comma, and evaluation order

`(f(xs), ...)` is the idiomatic "do this for every element". The comma operator sequences its left operand before its right, and that holds however the expression is grouped, so both the right fold and the left fold call `f` on the elements from first to last. That is a guarantee.

Expanding into function arguments gives no such guarantee. In `sink(f(xs)...)`, the arguments are indeterminately sequenced, and implementations do differ in practice. Expansion into a braced initializer list, as in the array trick, is evaluated left to right.

```cpp
#include <cstdio>

template<class... Ts> void sink(Ts...) {}

template<class... Ts> void show(Ts... xs) {
  (std::printf("%d", xs), ...);            // guaranteed 123 for show(1, 2, 3)
  sink((std::printf("%d", xs), 0)...);     // order unspecified
}
```

If the pattern's type might overload the comma operator, cast to `void`: `(void(f(xs)), ...)`. Overloaded commas are rare, but generic code that calls user functions is exactly where they show up.

## Packs and deduction

A function parameter pack at the end of the parameter list deduces one element per remaining argument, and its length is whatever is left. A function parameter pack anywhere else is a non-deduced context: it is never deduced from the call. Its elements must be given explicitly, and if it is the last template parameter and nothing is given, it is empty.

```cpp
template<class... Ts, class U> int last(Ts..., U u) { return u; }

int ok = last<int, int>(1, 2, 3);  // Ts = {int, int} explicitly, U = int deduced
// int no = last(1, 2, 3);         // error: Ts cannot be deduced from the call
```

Explicit arguments for a pack can also be extended by deduction: `f<int>(1, 2.0)` with `template<class... Ts> void f(Ts...)` gives `Ts = {int, double}`. Class template partial specializations use packs in the arguments, as in `template<class T, class... Rest> struct Count<T, Rest...>`, matching any non-empty list.

The most common pack in real code is a pack of forwarding references, `Args&&... args`, expanded as `std::forward<Args>(args)...`. Each element deduces independently, so one call can mix lvalues and rvalues, and the pattern `std::forward<Args>(args)` expands both packs in lockstep. Why that preserves value categories is the subject of the topic on forwarding references and perfect forwarding. C++26 pack indexing, `Ts...[0]`, has its own topic too.

## What to remember

- A pack can only be expanded; `pattern...` repeats the whole pattern once per element.
- Packs come as type, non-type, template template and function parameter packs, plus C++20 init-capture packs; `sizeof...` counts elements.
- Packs in one pattern expand in lockstep and must have equal lengths.
- Expansion is allowed only in list contexts and folds; `xs + 1...` fails to lex, so parenthesize.
- Unary folds group toward the dots; binary folds add an initial value used for empty packs.
- An empty unary fold is valid only for `&&` (true), `||` (false) and comma (`void()`).
- A comma fold evaluates left to right; expansion into function arguments does not guarantee order.
- Only a trailing function parameter pack is deduced from a call.

## Concept Map Outline

- **Variadic templates and folds:** A pack stands for zero or more arguments and can only be expanded.
  - **Kinds of pack:** Packs exist at every level a template can be parameterized.
    - **Template packs:** Type, non-type and template template packs: class... Ts, int... Ns.
    - **Function parameter packs:** Ts... xs; C++20 lambdas add init-capture packs [...ys = xs].
    - **sizeof...:** Counts elements as a std::size_t constant; unrelated to object sizes.
  - **Pack expansion:** pattern... repeats the whole pattern once per element.
    - **Pattern placement:** f(g(xs)...) calls g per element; g(f(xs...)) calls g once.
    - **Lockstep packs:** Several packs in one pattern must have the same length.
    - **List contexts only:** Arguments, initializers, bases, captures, using-declarations and folds.
    - **xs + 1...:** 1... lexes as one pp-number; write (xs + 1)... instead.
  - **Fold forms:** C++17 reduces a pack with one of 32 binary operators.
    - **Unary right:** (E op ...) groups as E1 op (E2 op E3).
    - **Unary left:** (... op E) groups as (E1 op E2) op E3.
    - **Binary folds:** (E op ... op I) and (I op ... op E) add an initial value.
    - **Operand restriction:** The operand is a cast-expression: parenthesize xs * 2 inside a fold.
  - **Empty packs:** Only three unary folds have a value for zero elements.
    - **&& and ||:** An empty && fold is true and an empty || fold is false.
    - **Comma:** An empty comma fold is void().
    - **Everything else:** Empty unary + or * is ill-formed; use a binary fold with an identity.
  - **Evaluation order:** Which expansions run their elements first to last.
    - **Comma fold:** (f(xs), ...) is sequenced left to right, in either fold direction.
    - **Call arguments:** sink(f(xs)...) evaluates the elements in unspecified order.
    - **Overloaded comma:** Cast to void, (void(f(xs)), ...), to bypass a user operator comma.
  - **Packs and deduction:** How a pack gets its length.
    - **Trailing pack:** A last function parameter pack deduces one element per remaining argument.
    - **Non-trailing pack:** Never deduced from the call; supply it explicitly.
    - **Forwarding packs:** Args&&... args with std::forward<Args>(args)... keeps each category.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.sizeof], [temp.variadic])

What is the value of `n`?

```cpp
template<class... Ts> constexpr auto count = sizeof...(Ts);

constexpr auto n = count<int, void, char[3]>;
```

A. 3
B. 8, the sum of the sizes on a typical 64-bit platform
C. Ill-formed: `void` cannot appear in a type pack
D. Ill-formed: `sizeof` cannot be applied to `void`

**Answer (A):** 3

**Why:** `sizeof...` counts the elements of a pack; it does not measure any type, so `void` and an array type are as good as any other element. The result is a `std::size_t` constant equal to 3. The size-related options confuse it with `sizeof`, which would indeed reject `void`.

### Question 2 [warmup] ([expr.prim.fold], [temp.variadic])

What does this program print?

```cpp
#include <cstdio>

template<class... Ts> int r(Ts... xs) { return (xs - ...); }
template<class... Ts> int l(Ts... xs) { return (... - xs); }

int main() { std::printf("%d %d\n", r(10, 4, 3), l(10, 4, 3)); }
```

A. `3 3`
B. `3 9`
C. `9 3`
D. `9 9`

**Answer (C):** `9 3`

**Why:** A unary right fold `(xs - ...)` groups toward the right: `10 - (4 - 3)`, which is 9. A unary left fold `(... - xs)` groups toward the left: `(10 - 4) - 3`, which is 3. The parentheses pile up on the side where the dots are. For an associative operator such as `+` both forms agree, which is why it is easy to forget that the choice matters.

### Question 3 [warmup] ([temp.variadic], [expr.prim.fold])

Is this program well-formed, and if so what does it return?

```cpp
template<class... Ts> int sum(Ts... xs) { return (xs + ...); }

int main() { return sum(); }
```

A. Well-formed; returns 0, the identity for `+`
B. Ill-formed: a unary fold over `+` with an empty pack has no value
C. Well-formed; returns an indeterminate value
D. Undefined behavior

**Answer (B):** Ill-formed: a unary fold over `+` with an empty pack has no value

**Why:** For an empty pack, a unary fold is defined only for `&&` (giving `true`), `||` (giving `false`) and the comma operator (giving `void()`). For `+` the instantiation is ill-formed, so `sum()` fails to compile. The identity value 0 was in the original fold-expression proposal but was removed before C++17. Write the binary fold `(xs + ... + 0)` to get 0 for an empty pack.

### Question 4 [tricky] ([expr.comma], [expr.call], [temp.variadic])

For the call `show(1, 2, 3)`, what does the standard guarantee about the output of lines #1 and #2?

```cpp
#include <cstdio>

template<class... Ts> void sink(Ts...) {}

template<class... Ts> void show(Ts... xs) {
  (std::printf("%d", xs), ...);         // #1
  sink((std::printf("%d", xs), 0)...);  // #2
}
```

A. Both print `123`
B. #1 prints `321`, because a right fold evaluates from the right; #2 is unspecified
C. #1 prints `123`; the order of #2 is unspecified
D. The order of both is unspecified

**Answer (C):** #1 prints `123`; the order of #2 is unspecified

**Why:** #1 expands to `printf(1), (printf(2), printf(3))`. The built-in comma operator sequences its left operand before its right however the operands are grouped, so the output is `123`. #2 expands into function arguments, which are indeterminately sequenced with respect to each other, so any order is permitted. The "right fold evaluates from the right" answer confuses grouping with evaluation order.

### Question 5 [tricky] ([lex.ppnumber], [temp.variadic])

Is the definition of `plus1` well-formed?

```cpp
#include <tuple>

template<class... Ts> auto plus1(Ts... xs) {
  return std::make_tuple(xs + 1...);
}
```

A. Yes: it expands to `make_tuple(x1 + 1, x2 + 1, ...)`
B. Yes, but it expands to `make_tuple(xs + 1, xs + 1, ...)` with the pack unexpanded
C. No: `1...` is lexed as a single preprocessing number, so the pack is never expanded
D. No: a pack expansion pattern cannot contain a literal

**Answer (C):** No: `1...` is lexed as a single preprocessing number, so the pack is never expanded

**Why:** Maximal munch in preprocessing turns `1...` into one pp-number, which cannot be converted to a valid token, so the code is ill-formed before templates are even considered; GCC reports too many decimal points. Patterns may contain literals freely, so writing `(xs + 1)...` or `xs + 1 ...` with a space gives the intended expansion of the first option.

### Question 6 [tricky] ([temp.deduct.call], [temp.deduct.type], [temp.param])

Which of the two calls is well-formed?

```cpp
template<class... Ts, class U> int last(Ts..., U u) { return u; }

int a = last<int, int>(1, 2, 3);  // #1
int b = last(1, 2, 3);            // #2
```

A. Both: `Ts` is deduced as `{int, int}` in #2
B. Only #2
C. Neither: a pack cannot be followed by another function parameter
D. Only #1

**Answer (D):** Only #1

**Why:** A function parameter pack that is not at the end of the parameter list is a non-deduced context, so `Ts` is never deduced from the call. In #1 `Ts` is given explicitly as `{int, int}`, the first two arguments match the pack, and `U` is deduced as `int` from the third. In #2 nothing supplies `Ts`, so deduction fails and #2 is ill-formed. The declaration itself is fine, because `U` can be deduced, which rules out the third option.

### Question 7 [standardese] ([temp.variadic], [stmt.return])

Each function is called with an empty pack in `main`. Which one makes the program ill-formed?

```cpp
template<class... Ts> bool a(Ts... xs) { return (... && xs); }
template<class... Ts> bool b(Ts... xs) { return (xs || ...); }
template<class... Ts> void c(Ts... xs) { return (xs, ...); }
template<class... Ts> int  d(Ts... xs) { return (xs * ...); }

int main() { a(); b(); c(); return d(); }
```

A. `a`
B. `b`
C. `c`
D. `d`

**Answer (D):** `d`

**Why:** [temp.variadic] gives values for exactly three empty unary folds: `&&` is `true`, `||` is `false` and the comma operator is `void()`, which is why `c` may `return` it from a `void` function. Any other operator, including `*`, has no fallback and the instantiation is ill-formed. The tempting choice is `c`, since returning an expression from a `void` function looks wrong, but returning a `void` expression is allowed.

### Question 8 [standardese] ([temp.variadic])

What does the alias `Z` denote?

```cpp
#include <utility>

template<class... Ts> struct List {};

template<class... Ts> struct Zip {
  template<class... Us> using with = List<std::pair<Ts, Us>...>;
};

using Z = Zip<int, char>::with<long>;
```

A. `List<std::pair<int, long>>`; the shorter pack decides the length
B. Ill-formed: the packs expanded by one pattern must have the same length
C. `List<std::pair<int, long>, std::pair<char, long>>`
D. `List<std::pair<int, long>, std::pair<char, void>>`

**Answer (B):** Ill-formed: the packs expanded by one pattern must have the same length

**Why:** The pattern `std::pair<Ts, Us>` names two packs, so they expand in lockstep, and [temp.variadic] requires every pack in one expansion to have the same number of elements. With two `Ts` and one `Us` the alias is ill-formed; GCC reports mismatched argument pack lengths. There is no truncation or padding. `Zip<int, char>::with<long, bool>` would be `List<std::pair<int, long>, std::pair<char, bool>>`.

# SFINAE and Concepts

> Trace how substitution failures prune candidates silently during C++17 template deduction, and how C++20 concepts replace enable_if with named atomic constraints and subsumption.

- **Source:** C++ Atlas (https://cppatlas.com/topics/sfinae-and-concepts)
- **Track:** Templates
- **Estimated reading time:** 10 minutes
- **ISO C++ clauses:** [temp.deduct] (https://eel.is/c++draft/temp.deduct), [temp.constr.decl] (https://eel.is/c++draft/temp.constr.decl), [temp.constr.atomic] (https://eel.is/c++draft/temp.constr.atomic), [temp.constr.order] (https://eel.is/c++draft/temp.constr.order), [expr.prim.req] (https://eel.is/c++draft/expr.prim.req), [over.match.viable] (https://eel.is/c++draft/over.match.viable), [meta.trans.other] (https://eel.is/c++draft/meta.trans.other)
- **cppreference links:** [SFINAE](https://en.cppreference.com/w/cpp/language/sfinae), [Constraints and concepts](https://en.cppreference.com/w/cpp/language/constraints), [requires expression](https://en.cppreference.com/w/cpp/language/requires), [std::enable_if](https://en.cppreference.com/w/cpp/types/enable_if), [std::void_t](https://en.cppreference.com/w/cpp/types/void_t), [Concepts library](https://en.cppreference.com/w/cpp/concepts), [Overload resolution](https://en.cppreference.com/w/cpp/language/overload_resolution)
- **Prerequisites:** overload-resolution, type-deduction-auto-decltype

Overload resolution across function templates requires a way to tell the compiler which type combinations a template actually supports. Before C++20, authors relied on **SFINAE** ("Substitution Failure Is Not An Error") to sabotage template signatures intentionally when types did not fit; C++20 replaced those tricks with **concepts**, turning constraints into first-class compile-time predicates with formal partial ordering.

## SFINAE and the immediate context boundary

When overload resolution tests a function template candidate, it substitutes deduced or explicit template arguments into the template's **immediate context**—its template parameter list, function parameter types, return type, `explicit(expr)`, and `noexcept(expr)` (`[temp.deduct]`). If substituting `T = int` makes the signature invalid (such as forming `int::iterator` or dividing by zero in a constant expression inside the signature), the compiler does **not** emit a compile error. Instead, it drops that candidate silently from the viable overload set.

Crucially, SFINAE stops at the immediate context boundary. Any error triggered while instantiating a helper **class template body** or the function's own body is a **hard error**, even if that instantiation began during signature substitution. For example, checking `typename Wrapper<T>::type` only invokes SFINAE if `Wrapper<T>` fails directly on `::type` lookup; if instantiating `Wrapper<T>` itself fails inside its member declarations, compilation aborts immediately.

## Pre-C++20 idioms: enable_if, void_t, and expression SFINAE

Three pre-C++20 idioms operationalized SFINAE across libraries:

- **`std::enable_if_t<Cond, T>`:** Defined only when `Cond` is `true` (`[meta.trans.other]`). When `Cond` is `false`, referencing `enable_if<false>::type` fails substitution cleanly.
- **`std::void_t<Args...>`:** Maps any pack of valid types to `void`, powering trait detection via partial class template specialization.
- **Expression SFINAE and `if constexpr`:** Placing `decltype(expr, void())` in a trailing return type tests valid expressions without calling them, while C++17 `if constexpr` discards untaken branches inside a single function body.

```cpp
#include <type_traits>
#include <utility>
#include <vector>

template <class T, std::enable_if_t<std::is_integral_v<T>, int> = 0>
int classify(T) { return 1; }

template <class T, std::enable_if_t<!std::is_integral_v<T>, int> = 0>
int classify(T) { return 2; }

template <class, class = void>
struct has_size : std::false_type {};

template <class T>
struct has_size<T, std::void_t<decltype(std::declval<const T&>().size())>>
    : std::true_type {};

static_assert(has_size<std::vector<int>>::value);
static_assert(!has_size<int>::value);
```

> **Pitfall.** Never write `template <class T, class = std::enable_if_t<Cond>> void f(T);` to distinguish two overloads. Default template arguments are **not** part of a function template's signature, so two overloads differing only in their default `enable_if_t` type redeclare the exact same function template and fail to compile. Use a non-type template parameter (`std::enable_if_t<Cond, int> = 0`) or constrain the return type instead.

## C++20 constraints, concepts, and requires-expressions

C++20 concepts move constraining predicates into explicit boolean compile-time clauses checked **before** overload conversion ranking (`[over.match.viable]`), producing readable diagnostics and eliminating manual mutual-exclusion flags (`!CondA && CondB`).

A template accepts constraints in four equivalent syntactic positions: constrained template-head parameters (`template <std::integral T>`), a `requires`-clause after the template parameter list, a trailing `requires`-clause after the function declarator (essential for constraining non-template member functions of class templates without turning them into templates), or abbreviated function templates (`void f(std::integral auto x)`).

A `requires`-expression (`[expr.prim.req]`) lets a concept or `requires`-clause test compile-time syntax directly using four kinds of requirements:

| Requirement kind | Syntax example | What it verifies |
| --- | --- | --- |
| Simple requirement | `a + b;` | Expression is well-formed (unevaluated) |
| Type requirement | `typename T::value_type;` | Nested type or specialization exists |
| Compound requirement | `{ c.size() } noexcept -> std::convertible_to<std::size_t>;` | Expression compiles, optional `noexcept`, return satisfies concept |
| Nested requirement | `requires !std::is_pointer_v<T>;` | Constant boolean expression evaluates to `true` |

```cpp
#include <concepts>
#include <cstddef>
#include <type_traits>

template <class C>
concept SizedContainer = requires(const C& c) {
    typename C::value_type;
    c.begin();
    { c.size() } noexcept -> std::convertible_to<std::size_t>;
    requires !std::is_pointer_v<C>;
};
```

Writing `requires requires(T x) { ... }` directly on a function combines two separate grammar tokens: the first `requires` starts a `requires`-clause (expecting a boolean constant expression), while the second starts a `requires`-expression that evaluates to `bool`. Factor reusable predicates into named `concept` declarations instead of scattering anonymous `requires requires` clauses across signatures.

> **Pitfall.** Inside a `requires`-expression, omitting the nested `requires` keyword turns a boolean trait check into a simple requirement! Writing `std::same_as<T, int>;` without a leading `requires` only tests whether the expression `std::same_as<T, int>` compiles—and since it validly produces a `bool` (even `false`), the requirement passes for `double` too.

## Constraint normalization and subsumption

SFINAE cannot rank overlapping conditions—if two overloads both accept `int`, overload resolution fails with ambiguity unless you explicitly negate one condition inside the other. Concepts solve that via **subsumption** (`[temp.constr.order]`): if two constrained candidates match equally well on parameter conversions, the **more constrained** candidate wins automatically.

> **Mental model.** Subsumption does not inspect runtime semantics or algebra; it treats named concepts as reusable building blocks. Candidate `P` subsumes candidate `Q` only when every atomic constraint in `Q` appears inside `P` from the exact same named concept declaration.

During comparison, the compiler normalizes each candidate's constraint expression into conjunctions (`&&`) and disjunctions (`||`) of **atomic constraints** (`[temp.constr.atomic]`). An atomic constraint is identified by both its source-code expression location and its template parameter mapping—meaning two inline `sizeof(T) >= 4` expressions in separate `requires` clauses create two distinct atomic constraints that **never** subsume one another!

```cpp
#include <concepts>
#include <type_traits>

template <class T>
concept Integral = std::integral<T>;

template <class T>
concept SignedIntegral = Integral<T> && std::is_signed_v<T>;

constexpr int pick(Integral auto) { return 1; }
constexpr int pick(SignedIntegral auto) { return 2; } // subsumes Integral!

static_assert(pick(42u) == 1);
static_assert(pick(42) == 2);
```

> **Standardese.** Under `[temp.constr.atomic]`, only concept-ids expand recursively during constraint normalization; constant expressions involving type traits like `std::is_signed_v<T> && std::is_integral_v<T>` are opaque single atoms unless composed from named `concept` declarations.

Because `SignedIntegral<T>` expands directly to the shared named concept `Integral<T>` conjoined with `std::is_signed_v<T>`, `pick(SignedIntegral auto)` strictly subsumes `pick(Integral auto)` and resolves `pick(42)` without ambiguity. Note also that since C++23 (`P2593R1`), `static_assert(false)` inside an uninstantiated `if constexpr` branch or template body is valid until instantiated, complementing concepts for clean compile-time error messages.

## What to remember

- SFINAE applies only within the immediate context of template substitution; errors inside instantiated class or function bodies remain hard errors.
- Avoid `class = std::enable_if_t<...>` as a default template argument for overloading—it creates duplicate signatures; use non-type template parameters or constraints instead.
- Inside a `requires`-expression, expressions are unevaluated; always prefix boolean predicate assertions with nested `requires` so you check truth value, not mere syntactic validity.
- Factor shared predicates into named `concept` definitions—subsumption matches normalized atomic constraints by declaration identity, not boolean equivalence.
- Constraint satisfaction filters candidates before conversion ranking, and a more constrained candidate beats a less constrained one cleanly without ambiguity.

## Concept Map Outline

- **SFINAE & Concepts:** Compile-time template constraints evolved from silent SFINAE substitution failures to ordered C++20 concept lattices.
  - **SFINAE Rules:** Invalid type or expression formation in a signature drops a candidate without failing the build.
    - **Immediate Context:** Template parameters, function parameters, return types, and explicit/noexcept clauses participate in SFINAE.
    - **Hard Instantiation Errors:** Failures inside instantiated helper class bodies or function bodies halt compilation immediately.
    - **Expression SFINAE:** Trailing decltype expressions verify member calls or operators without evaluating operands.
  - **Pre-C++20 Idioms:** Library patterns built explicit opt-in and trait detection on top of SFINAE.
    - **std::enable_if:** Produces a nested type only when a compile-time boolean condition evaluates to true.
    - **Default Arg Signature Trap:** Overloads differing only by a default template type argument collide as identical redeclarations.
    - **std::void_t Detection:** Maps valid type expressions to void to select specialized type traits cleanly.
    - **if constexpr Branches:** Discards untaken compile-time branches inside a single template body since C++17.
  - **C++20 Syntax:** Constraints evaluate before overload conversion sequences and yield clear diagnostics.
    - **Named Concepts:** Reusable compile-time boolean predicates that serve as shared atoms for subsumption.
    - **Requires-Clauses:** Attach compile-time boolean constraints on template heads or trailing member signatures.
    - **Abbreviated Auto:** Constrained auto parameters synthesize constrained function templates concisely.
    - **Requires-Expressions:** Evaluate syntactic validity of expressions and types at compile time, returning a bool.
  - **Requirement Kinds:** Inside a requires-expression, four distinct clauses check syntax, types, returns, and values.
    - **Simple & Type:** Verify that expressions compile and nested or specialized types exist without evaluating operands.
    - **Compound Return Check:** Enforce expression validity, optional noexcept guarantee, and return type concept satisfaction.
    - **Nested Requires Trap:** Omitting nested requires checks only whether a boolean trait expression compiles, not whether it is true.
  - **Subsumption Ordering:** Overlapping constrained templates resolve ambiguity through normalized atomic constraint inclusion.
    - **Atomic Constraints:** Constraints normalize down to source-located predicates paired with their template parameter mapping.
    - **DNF and CNF Normalization:** The compiler expands named concepts into conjunctions and disjunctions before comparing candidates.
    - **More Constrained Wins:** A candidate whose normalized constraints include all of another's wins overload resolution cleanly.

## Standardese Quiz Questions

### Question 1 [warmup] ([temp.deduct], [meta.trans.other])

During overload resolution, what happens when `std::enable_if_t<false, int>` is formed in a function template's return type?

A. Compilation halts immediately with an error inside namespace std
B. Substitution fails in the immediate context and that candidate is silently removed from the overload set
C. The return type defaults to void and the template remains viable
D. std::enable_if_t throws std::bad_typeid at runtime

**Answer (B):** Substitution fails in the immediate context and that candidate is silently removed from the overload set

**Why:** Under [temp.deduct], when `Cond` is false, `std::enable_if<false, int>` has no member `type`. Because this failure occurs in the immediate context of the function template's return type, SFINAE removes the candidate silently.

### Question 2 [warmup] ([dcl.fct], [temp.constr.decl])

How do `template <class T> void f(T x) requires std::integral<T>;` and `void f(std::integral auto x);` compare in C++20?

A. Both declare function templates constrained by std::integral on the deduced parameter type
B. Only the abbreviated form works with concepts; trailing requires only checks runtime values
C. Abbreviated auto allows virtual member functions whereas trailing requires forbids them
D. Abbreviated auto performs type erasure like std::any instead of template instantiation

**Answer (A):** Both declare function templates constrained by std::integral on the deduced parameter type

**Why:** Under [dcl.fct] and [temp.constr.decl], an abbreviated function template using a type-constraint before `auto` introduces an invented constrained template type parameter with the same constraint semantics.

### Question 3 [tricky] ([temp.over.link], [temp.param])

Why does defining these two overloads with default template type arguments fail to compile?

```cpp
template <class T, class = std::enable_if_t<std::is_integral_v<T>>>
void log(T v) {}

template <class T, class = std::enable_if_t<!std::is_integral_v<T>>>
void log(T v) {}
```

A. std::enable_if_t cannot be placed inside a template parameter list
B. Both conditions evaluate to true when T is int
C. Default template arguments are not part of a function template's signature, so the second declaration redefines the first
D. is_integral_v requires C++20 concepts to negate

**Answer (C):** Default template arguments are not part of a function template's signature, so the second declaration redefines the first

**Why:** Two function templates with identical parameter lists and template parameter kinds have the exact same signature regardless of default template arguments ([temp.over.link]). The second `log` illegally redefines the first template with a different default argument.

### Question 4 [tricky] ([expr.prim.req.simple], [expr.prim.req.nested])

What does `AlwaysTrue<double>` evaluate to in the concept definition below?

```cpp
template <class T>
concept AlwaysTrue = requires {
    std::same_as<T, int>;
};
```

A. false, because double is not the same type as int
B. Ill-formed: concepts cannot appear inside a requires-expression
C. false, because std::same_as evaluates at runtime
D. true, because without a nested `requires`, the line only checks whether the expression `std::same_as<double, int>` compiles

**Answer (D):** true, because without a nested `requires`, the line only checks whether the expression `std::same_as<double, int>` compiles

**Why:** Inside a requires-expression, `std::same_as<T, int>;` without a leading `requires` is a simple requirement ([expr.prim.req.simple]). Since `std::same_as<double, int>` is a valid bool expression yielding `false`, the simple requirement succeeds and `AlwaysTrue<double>` is `true`!

### Question 5 [standardese] ([temp.constr.atomic], [temp.constr.order])

Why is calling `pick(42)` ambiguous between these two constrained overloads?

```cpp
template <class T> requires (sizeof(T) >= 2)
void pick(T) {}

template <class T> requires (sizeof(T) >= 2 && std::integral<T>)
void pick(T) {}
```

A. sizeof(T) >= 2 is not a constant expression when T is deduced
B. The two inline `sizeof(T) >= 2` expressions are separate atomic constraints with distinct source identities, so neither subsumes the other
C. Subsumption only applies to class templates, never function templates
D. std::integral<T> cannot be combined with && inside a requires clause

**Answer (B):** The two inline `sizeof(T) >= 2` expressions are separate atomic constraints with distinct source identities, so neither subsumes the other

**Why:** Under [temp.constr.atomic] and [temp.constr.order], subsumption compares normalized atomic constraints by declaration identity and parameter mapping—not mathematical equivalence. Only factoring `sizeof(T) >= 2` into a shared named concept enables subsumption.

### Question 6 [standardese] ([temp.deduct])

Which failure triggers a hard compilation error rather than being silently discarded by SFINAE when instantiating for `T = int`?

A. Forming `typename T::value_type` directly in a function template's return type
B. Forming an invalid call `decltype(std::declval<T&>().push_back(0))` in a trailing return type
C. A static_assert or invalid typedef triggered inside a helper struct's class definition instantiated during substitution
D. Failing a concept check in a function template's trailing requires-clause

**Answer (C):** A static_assert or invalid typedef triggered inside a helper struct's class definition instantiated during substitution

**Why:** Under [temp.deduct], SFINAE covers only errors in the immediate context of the function type and template parameter expressions. Instantiating a separate class template body to inspect its members leaves the immediate context and causes a hard error.

# SFINAE

> When substituting template arguments into a function template's declaration produces an invalid type or expression, that template quietly leaves the overload set. Only failures in the immediate context of the signature count; everything else is a hard error.

- **Source:** C++ Atlas (https://cppatlas.com/topics/sfinae)
- **Track:** Templates
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [temp.deduct.general] (https://eel.is/c++draft/temp.deduct.general), [temp.deduct.call] (https://eel.is/c++draft/temp.deduct.call), [temp.over] (https://eel.is/c++draft/temp.over), [temp.over.link] (https://eel.is/c++draft/temp.over.link), [temp.param] (https://eel.is/c++draft/temp.param), [meta.trans.other] (https://eel.is/c++draft/meta.trans.other), [dcl.spec.auto] (https://eel.is/c++draft/dcl.spec.auto)
- **cppreference links:** [SFINAE](https://en.cppreference.com/w/cpp/language/sfinae), [std::enable_if](https://en.cppreference.com/w/cpp/types/enable_if), [std::void_t](https://en.cppreference.com/w/cpp/types/void_t), [std::experimental::is_detected](https://en.cppreference.com/w/cpp/experimental/is_detected), [Template argument deduction](https://en.cppreference.com/w/cpp/language/template_argument_deduction)
- **Prerequisites:** template-argument-deduction, overload-resolution

## The one idea

Before overload resolution can compare a function template with other candidates, the compiler has to work out its template arguments and substitute them into the template's declaration: the parameter types, the return type, the template parameter list, and since C++20 the `explicit` specifier. If that substitution produces something that cannot exist, such as `int::type`, a pointer to a reference, or a call to a member that is not there, the template is simply dropped from the candidate set. Substitution failure is not an error. If no candidate survives, the call fails as usual with "no matching function".

That is the entire mechanism. Everything clever built on it, from `enable_if` to the detection idiom, is a way of writing a condition so that it turns into an invalid type or expression in the signature when the condition is false.

> **Mental model.** SFINAE looks only at the declaration the compiler is substituting into, never at what substitution sets in motion. A failure written directly in the signature removes the candidate. A failure that happens inside some other template the signature had to instantiate, or inside a function body, stops compilation.

## The immediate context: signature, not body

The standard calls the region where failures are soft the immediate context of the function type, its template parameter types and its `explicit` specifier. It does not define the term precisely, but its examples and the long-standing compiler consensus agree on the boundary. Forming the type `typename T::value_type` is in the immediate context. Instantiating a class template so that you can look inside it is a side effect, and an error inside that class's definition is not.

```cpp
template <class T>
struct Checked {
  static_assert(sizeof(T) > 1, "too small");
  using type = int;
};

template <class T> typename Checked<T>::type h(T) { return 0; }
long h(...) { return 1; }

// h('c');  // hard error: the static_assert fires while instantiating
//          // Checked<char>; the h(...) fallback is never reached
```

Function bodies are never part of the immediate context. That includes bodies the compiler has to instantiate just to learn a deduced return type. If a signature asks for the type of a call to a function declared with `auto`, the callee's body is instantiated, and an error there is final.

```cpp
#include <utility>

template <class T> auto value_of(T t) { return t.value; }

template <class T>
auto probe(int) -> decltype(value_of(std::declval<T>()), true) { return true; }
template <class T> bool probe(...) { return false; }

// probe<int>(0);  // hard error inside value_of's body, not a quiet false
```

C++20 adds one explicit exclusion: the body of a lambda expression is not part of the immediate context, so a lambda inside `decltype` cannot be used to probe for validity.

Substitution also happens in a defined order. Since C++11 (through CWG 1227), it proceeds in lexical order and stops at the first failure. Where you put a constraint can therefore decide whether a later, dangerous instantiation happens at all.

```cpp
template <class T> struct A { using X = typename T::X; };

template <class T> typename T::X f(typename A<T>::X);
template <class T> int f(...) { return 1; }

template <class T> auto g(typename A<T>::X) -> typename T::X;
template <class T> int g(...) { return 2; }

void use() {
  f<int>(0);    // OK: the return type int::X fails first, A<int> is never touched
  // g<int>(0); // error: the parameter is substituted first and instantiates A<int>
}
```

## `enable_if` and where to put it

`std::enable_if<B, T>` has a member `type` equal to `T` only when `B` is true. Naming `std::enable_if_t<B, T>` when `B` is false names a member that does not exist, which is a substitution failure. There are three places to put it.

- **The return type**: `std::enable_if_t<cond, R> f(T)`. Clear, but unusable for constructors and conversion operators, and it clutters the signature people read.
- **An extra function parameter with a default argument**: `void f(T, std::enable_if_t<cond>* = nullptr)`. It works for constructors, but it changes the function's arity and leaks into function pointer types.
- **A template parameter**: either a type parameter with a default, or a non-type parameter. This is the idiomatic choice, and the form you pick matters.

The type-parameter form has a trap. Default template arguments are not part of a function template's signature, so two templates that differ only in their defaults are the same template declared twice.

```cpp
#include <cstdio>
#include <type_traits>

// template <class T, class = std::enable_if_t<std::is_integral_v<T>>>
// void f(T) {}
// template <class T, class = std::enable_if_t<std::is_floating_point_v<T>>>
// void f(T) {}   // error: redefinition, both are template <class, class> void f(T)

template <class T, std::enable_if_t<std::is_integral_v<T>, int> = 0>
void g(T) { std::puts("integral"); }
template <class T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
void g(T) { std::puts("floating"); }   // OK: the parameter's type differs
```

In the non-type form, the condition is part of the template parameter's type, and two template parameter lists are equivalent only if their parameters have equivalent types. The two `g` templates are therefore distinct, and each one removes itself when its condition fails.

> **Pitfall.** `enable_if` only works on a condition that depends on a template parameter of the function template being substituted. A member function of a class template that uses the class's `T` in `enable_if_t<std::is_integral_v<T>, int>` is not being deduced at all: instantiating the class with `double` produces an invalid declaration, which is a hard error. Give the member its own defaulted parameter, `template <class U = T, ...>`, so there is something to substitute.

## Expression SFINAE with `decltype`

C++11 made it explicit that arbitrary expressions in a signature participate in substitution. A trailing `decltype` lets a template ask "would this expression compile?" and name the resulting type at the same time.

```cpp
#include <cstdio>
#include <string>

template <class T>
auto describe(const T& t) -> decltype(t.size(), void()) { std::printf("size %zu\n", t.size()); }
void describe(...) { std::puts("no size"); }

void demo() {
  describe(std::string("abc"));  // size 3
  describe(42);                  // no size
}
```

The comma operator lets the expression check one thing and yield another type. The `void()` on the right is not decoration: if `t.size()` returned a class type with an overloaded `operator,`, the comma would call it. A `void` operand cannot be passed to a user-defined comma operator, so `void()` forces the built-in one.

Access checking is part of substitution too. If `size` exists but is private, the expression is invalid in the context of the substitution, and the template is removed rather than diagnosed.

## `void_t` and the detection idiom

For type traits, the same trick moves into class template partial specialization. Matching a partial specialization also deduces and substitutes, so an invalid type in its argument list makes that specialization not match. `std::void_t`, added in C++17, maps any list of valid types to `void`, which turns "these types are well-formed" into "this specialization's argument is `void`".

```cpp
#include <type_traits>
#include <utility>

template <class, class = void>
struct has_size : std::false_type {};

template <class T>
struct has_size<T, std::void_t<decltype(std::declval<T&>().size())>> : std::true_type {};

class Hidden { int size() const { return 0; } };
struct Open { int size() const { return 0; } };

static_assert(!has_size<int>::value);
static_assert(!has_size<Hidden>::value);  // private: a substitution failure, not an error
static_assert(has_size<Open>::value);
```

The primary template supplies `void` as the default second argument. When the expression is valid, the specialization's argument is also `void`, it matches, and it is more specialized. When the expression is invalid, only the primary is left.

The Library Fundamentals TS v2 generalized this as the detection idiom: `std::experimental::is_detected<Op, Args...>` takes an alias template `Op` describing the expression, plus `detected_t` and `detected_or` to fetch the resulting type with a fallback. It never made it into the standard library, because concepts arrived and do the job natively.

## Hard errors and soft failures

A useful checklist for the boundary:

| Soft failure: candidate removed | Hard error: compilation stops |
| --- | --- |
| Naming a member type that does not exist | A `static_assert` or invalid member inside a class template instantiated along the way |
| An invalid expression inside `decltype` or `sizeof` in the signature | An error in a body instantiated to deduce an `auto` return type |
| A pointer to a reference, an array of `void`, a negative array bound | An error in a function body after the candidate was chosen |
| An inaccessible member named in the signature | A lambda body used inside the signature (C++20) |
| A non-type argument that does not convert to the parameter's type | An `enable_if` on a class template parameter in a non-template member |

> **Standardese.** [temp.deduct.general] states that only invalid types and expressions in the immediate context of the function type, its template parameter types and its `explicit` specifier cause deduction failure, and that side effects of substitution, such as instantiating class template specializations or implicitly defining member functions, are not in the immediate context. It also says that if different declarations of the same template would substitute in different lexical orders with different instantiation results, the program is ill-formed, no diagnostic required.

The other consequence of this boundary is that SFINAE says nothing about whether the body would compile. A template that passes every check in its signature can still fail when its definition is instantiated. Constraining the signature is a promise you make by hand.

## Concepts replace most of it

C++20 constraints express the same conditions directly. A requires-clause is checked after deduction, an unsatisfied constraint removes the candidate just as a substitution failure would, and constraints also take part in choosing between overloads that are both viable, which SFINAE cannot do without contortions such as mutually exclusive conditions.

```cpp
#include <concepts>
#include <cstdio>

void h(std::integral auto) { std::puts("integral"); }
void h(std::floating_point auto) { std::puts("floating"); }  // no redeclaration trap
```

Constraints remove the redeclaration trap, since different constraints make different templates; they produce diagnostics that name the failed requirement; and they work on non-template members of class templates. What they do not change is the immediate-context rule: an invalid expression inside a requires-expression makes it false, while an error inside something that expression instantiates is still a hard error. SFINAE remains the tool for C++17 and earlier code, for partial specializations written as traits, and for reading the standard library. The concepts-and-constraints topic covers the replacement in depth.

## What to remember

- Substitution failure removes a function template from the candidate set; if nothing viable remains, the call still fails.
- Only the immediate context counts: the signature, template parameter types and `explicit` specifier, not bodies, instantiated classes or lambda bodies.
- Substitution runs in lexical order and stops at the first failure, so placement can prevent a dangerous instantiation.
- Deduced `auto` return types instantiate the body, so probing them is a hard error.
- Default template arguments are not part of the signature; use `std::enable_if_t<cond, int> = 0`, not `class = std::enable_if_t<cond>`, for overloads.
- `enable_if` on a class template's own parameter in a member is a hard error; the condition must depend on the function template's parameters.
- Write `decltype(expr, void())` to sidestep overloaded commas; access violations in the signature are soft failures.
- `void_t` plus a partial specialization is the C++17 detection idiom; concepts and requires-expressions are its C++20 replacement.

## Concept Map Outline

- **SFINAE:** An invalid type or expression produced by substitution into a signature removes that template from overload resolution.
  - **Immediate context:** Only failures in the function type, template parameter types and explicit specifier are soft.
    - **Signature, not body:** Function bodies are never checked by substitution; errors there are hard.
    - **Instantiated classes:** An error inside a class template instantiated during substitution is a hard error.
    - **auto return types:** Asking for a deduced return type instantiates the body, so probing it is a hard error.
    - **Lambda bodies (C++20):** A lambda in the signature is not part of the immediate context.
  - **Substitution order:** Since CWG 1227, substitution runs in lexical order and stops at the first failure.
    - **Early fail is safe:** A failing return type before a parameter prevents that parameter's instantiations.
    - **Differing orders:** Redeclarations that substitute in different orders with different results are IFNDR.
  - **enable_if:** enable_if_t<B, T> names T when B is true and nothing when false, failing substitution.
    - **Return type:** Simple, but impossible for constructors and conversion functions.
    - **Defaulted parameter:** Works for constructors but changes arity and function pointer types.
    - **Template parameter:** Idiomatic; use the non-type form enable_if_t<B, int> = 0.
    - **Redeclaration trap:** Defaults are not in the signature, so class = enable_if_t<...> twice is a redefinition.
    - **Class parameter trap:** A non-template member using the class's T in enable_if is a hard error.
  - **Expression SFINAE:** Since C++11, any invalid expression in the signature counts as a substitution failure.
    - **decltype(e, void()):** Checks e and yields void; the void() blocks an overloaded comma operator.
    - **Access checks:** Naming an inaccessible member during substitution is a soft failure.
  - **Detection idiom:** Partial specialization matching also substitutes, so traits can test validity.
    - **void_t (C++17):** Maps any valid types to void so a specialization matches the primary's default.
    - **is_detected:** Library Fundamentals TS v2 helper; never standardized, superseded by concepts.
  - **Concepts replace it:** C++20 requires-clauses state conditions directly and also rank overloads.
    - **No redeclaration trap:** Different constraints make different templates, so overloads just work.
    - **Same boundary:** Errors inside what a requires-expression instantiates are still hard errors.

## Standardese Quiz Questions

### Question 1 [warmup] ([temp.deduct.general], [temp.over])

What happens when this program is compiled?

```cpp
template <class T>
typename T::value_type first(const T& c) { return *c.begin(); }

int main() { return first(42); }
```

A. It compiles; SFINAE makes `first` return a default `int`
B. Ill-formed: there is no matching function for `first(42)`
C. Ill-formed: a hard error inside the body of `first`
D. Undefined behavior

**Answer (B):** Ill-formed: there is no matching function for `first(42)`

**Why:** Substituting `T = int` into the return type forms `int::value_type`, which is a substitution failure, so `first` is removed from the candidate set. SFINAE only removes candidates; with nothing left, the call is ill-formed with the ordinary "no matching function" diagnostic. The body is never instantiated, so there is no error inside it.

### Question 2 [warmup] ([temp.over.link], [temp.param], [basic.def.odr])

Is this program well-formed?

```cpp
#include <type_traits>

template <class T, class = std::enable_if_t<std::is_integral_v<T>>>
void f(T) {}

template <class T, class = std::enable_if_t<std::is_floating_point_v<T>>>
void f(T) {}

int main() { f(1); }
```

A. Well-formed: the second template is removed for `int`, the first is called
B. Ill-formed: the call `f(1)` is ambiguous
C. Ill-formed: the second definition redefines the same function template
D. Well-formed, but which overload runs is unspecified

**Answer (C):** Ill-formed: the second definition redefines the same function template

**Why:** Default template arguments are not part of a function template's signature, so both declarations are `template <class, class> void f(T)`, and the second is a redefinition of the first. The error is reported at the declaration, before any call is considered. Writing the condition as a non-type parameter, `std::enable_if_t<cond, int> = 0`, makes the template parameter types differ and gives two distinct templates.

### Question 3 [warmup] ([temp.deduct.general], [meta.trans.other])

What does this program print?

```cpp
#include <cstdio>
#include <type_traits>
#include <utility>

template <class, class = void>
struct has_size : std::false_type {};
template <class T>
struct has_size<T, std::void_t<decltype(std::declval<T&>().size())>> : std::true_type {};

class Hidden { int size() const { return 0; } };
struct Open { int size() const { return 0; } };

int main() { std::printf("%d %d\n", has_size<Hidden>::value, has_size<Open>::value); }
```

A. `0 1`
B. `1 1`
C. Nothing: ill-formed because `Hidden::size` is private
D. `0 0`

**Answer (A):** `0 1`

**Why:** Access checking is done as part of substitution, so naming the private `Hidden::size` from the partial specialization is an invalid expression in the immediate context, and the specialization simply does not match. `has_size<Hidden>` falls back to the primary template and is false. The tempting "ill-formed" answer was how some pre-C++11 compilers behaved; C++11 made access failures soft.

### Question 4 [tricky] ([temp.deduct.general], [temp.inst])

What happens when this program is compiled?

```cpp
template <class T>
struct Checked {
  static_assert(sizeof(T) > 1, "too small");
  using type = int;
};

template <class T> typename Checked<T>::type h(T) { return 0; }
long h(...) { return 1; }

int main() { return h('c'); }
```

A. Ill-formed: the `static_assert` fires while instantiating `Checked<char>`
B. It compiles and `main` returns 1, because the template is removed
C. It compiles and `main` returns 0
D. Ill-formed: the call is ambiguous

**Answer (A):** Ill-formed: the `static_assert` fires while instantiating `Checked<char>`

**Why:** To form `typename Checked<char>::type`, the compiler must instantiate `Checked<char>`, and the `static_assert` inside that class is not in the immediate context of `h`'s signature. Errors in side effects of substitution, such as instantiating a class template, are hard errors, so the fallback `h(...)` never gets a chance. The first option is what people expect when they think of SFINAE as "any error during overload resolution".

### Question 5 [tricky] ([temp.deduct.general], [dcl.spec.auto])

What happens when this program is compiled?

```cpp
#include <cstdio>
#include <utility>

template <class T> auto value_of(T t) { return t.value; }

template <class T>
auto probe(int) -> decltype(value_of(std::declval<T>()), true) { return true; }
template <class T> bool probe(...) { return false; }

int main() { std::printf("%d\n", probe<int>(0)); }
```

A. It prints `0`
B. It prints `1`
C. Ill-formed: `value_of<int>` must be instantiated to deduce its return type, and `t.value` is invalid there
D. Ill-formed, no diagnostic required

**Answer (C):** Ill-formed: `value_of<int>` must be instantiated to deduce its return type, and `t.value` is invalid there

**Why:** `value_of(std::declval<int>())` is a valid call as far as its declaration goes, but the type of the call is not known until the placeholder return type is deduced, which requires instantiating the body. Errors in that body are outside the immediate context of `probe`, so they are hard errors rather than a quiet `0`. A trailing `-> decltype(t.value)` on `value_of` would have moved the check into its signature and made `probe` print `0`.

### Question 6 [tricky] ([temp.inst], [temp.deduct.general])

Which line, if any, makes this translation unit ill-formed?

```cpp
#include <type_traits>

template <class T>
struct W {
  std::enable_if_t<std::is_integral_v<T>, int> get() { return 0; }
};

W<int> a;     // #1
W<double> b;  // #2
```

A. Neither: `get` is simply removed from `W<double>`
B. Only #2
C. Only #1
D. Neither, as long as `b.get()` is never called

**Answer (B):** Only #2

**Why:** `get` is not a template, so nothing is deduced or substituted when it is used. Instantiating the class `W<double>` instantiates the declarations of its members, and the declaration of `get` names `std::enable_if<false, int>::type`, which does not exist: a hard error that makes the translation unit ill-formed at #2. Making `get` a template with its own defaulted parameter, such as `template <class U = T>`, moves the condition into a substitution and turns it into SFINAE.

### Question 7 [standardese] ([temp.deduct.general])

Under the C++23 rules for the order of substitution, which of the two calls in `use` is ill-formed?

```cpp
template <class T> struct A { using X = typename T::X; };

template <class T> typename T::X f(typename A<T>::X);
template <class T> int f(...) { return 1; }

template <class T> auto g(typename A<T>::X) -> typename T::X;
template <class T> int g(...) { return 2; }

void use() {
  f<int>(0);
  g<int>(0);
}
```

A. Both
B. Only `f<int>(0)`
C. Neither: both fall back to the `(...)` overloads
D. Only `g<int>(0)`

**Answer (D):** Only `g<int>(0)`

**Why:** Substitution proceeds in lexical order and stops when it hits a failure. For `f`, the return type `int::X` comes first and fails softly, so `A<int>` is never instantiated and the `(...)` overload is chosen. For `g`, the trailing return type comes after the parameter, so `A<int>::X` is substituted first, which instantiates `A<int>` and fails inside the class: a hard error, so `g<int>(0)` is ill-formed. The two declarations look equivalent, which is why "both" or "neither" is tempting.

### Question 8 [standardese] ([temp.deduct.general], [dcl.spec.auto])

Which of these, encountered while substituting into a function template's declaration in C++23, is a substitution failure rather than a hard error?

A. A `static_assert` failing inside a class template that the return type instantiates
B. An invalid expression in the body of a lambda that appears inside a `decltype` in the return type
C. An invalid member access in the body of a function with a deduced `auto` return type that the signature calls
D. Naming a private member type of a class in the return type, from outside that class

**Answer (D):** Naming a private member type of a class in the return type, from outside that class

**Why:** Access checking is part of the substitution process, so an inaccessible name in the signature is an invalid type in the immediate context and removes the candidate. The other three all happen outside the immediate context: instantiating a class template is a side effect, C++20 says a lambda body is not part of the immediate context, and deducing an `auto` return type instantiates the function's body.

# Concepts and constraints

> A concept is a named compile-time predicate on template arguments, and a constraint is a predicate a template must satisfy before it can be used. The compiler breaks constraints into atomic pieces, and that decomposition, not the meaning of the expressions, decides which overload is more constrained.

- **Source:** C++ Atlas (https://cppatlas.com/topics/concepts-and-constraints)
- **Track:** Templates
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [temp.concept] (https://eel.is/c++draft/temp.concept), [temp.constr.constr] (https://eel.is/c++draft/temp.constr.constr), [temp.constr.atomic] (https://eel.is/c++draft/temp.constr.atomic), [temp.constr.decl] (https://eel.is/c++draft/temp.constr.decl), [temp.constr.normal] (https://eel.is/c++draft/temp.constr.normal), [temp.constr.order] (https://eel.is/c++draft/temp.constr.order), [expr.prim.req] (https://eel.is/c++draft/expr.prim.req), [dcl.fct] (https://eel.is/c++draft/dcl.fct), [res.on.requirements] (https://eel.is/c++draft/res.on.requirements)
- **cppreference links:** [Constraints and concepts](https://en.cppreference.com/w/cpp/language/constraints), [Requires expression](https://en.cppreference.com/w/cpp/language/requires), [Concepts library](https://en.cppreference.com/w/cpp/concepts), [Placeholder type specifiers](https://en.cppreference.com/w/cpp/language/auto), [Function template (abbreviated function templates)](https://en.cppreference.com/w/cpp/language/function_template)
- **Prerequisites:** sfinae, template-argument-deduction

## The one idea

A constraint is a compile-time boolean condition attached to a template. After template arguments are deduced and substituted, the constraint is checked; if it is not satisfied, the template is not a viable candidate. A concept is a named, reusable constraint: `template <class T> concept C = expression;`.

That much is SFINAE with better spelling. The new part is ordering. When two candidates are otherwise equally good, the compiler prefers the one whose constraints *subsume* the other's. To decide subsumption it does not reason about what your expressions mean. It normalizes each constraint into a tree of conjunctions and disjunctions of **atomic constraints**, and compares atoms by identity: the same expression written at the same place in the source.

> **Mental model.** Constraints are checked by evaluation and ordered by structure. Satisfaction asks whether each atom is valid and true for these arguments. Subsumption asks whether one tree of atoms logically implies the other, treating atoms as opaque symbols that are equal only when they come from the same spot in the source.

## Concepts and requires-clauses

A concept definition is a template whose body is a constraint expression. A concept cannot be constrained itself, cannot be explicitly specialized, and cannot refer to itself. Naming one, as in `std::integral<int>`, is a prvalue of type `bool`, so concepts work in `static_assert` and `if constexpr` too.

Constraints attach to a template in four spellings, which can be combined:

```cpp
#include <concepts>

template <std::integral T> void a(T);                 // type-constraint
template <class T> requires std::integral<T> void b(T); // requires-clause
template <class T> void c(T) requires std::integral<T>; // trailing requires-clause
void d(std::integral auto);                             // constrained placeholder
```

A requires-clause has a deliberately narrow grammar: its operands must be primary expressions, such as a concept-id, a literal, a name, or anything in parentheses, joined by `&&` and `||`. That keeps a trailing clause from swallowing what follows it, and it surprises people who write arithmetic.

```cpp
// template <class T> requires sizeof(T) > 4 void f(T);  // error: needs parentheses
template <class T> requires (sizeof(T) > 4) void f(T);    // OK
```

## Requires-expressions: four kinds of requirement

A requires-expression is a `bool` prvalue that is true when every requirement in its body is valid for the given arguments. It can introduce parameters, which are never evaluated and exist only to write expressions with.

```cpp
#include <concepts>
#include <cstddef>
#include <type_traits>

template <class T>
concept Container = requires(T c, const T cc) {
  typename T::value_type;                               // type requirement
  c.clear();                                            // simple requirement
  { cc.size() } noexcept -> std::same_as<std::size_t>;  // compound requirement
  requires std::is_default_constructible_v<T>;          // nested requirement
};
```

A **simple** requirement asserts that an expression is valid. A **type** requirement asserts that a type can be named. A **compound** requirement asserts validity, optionally that the expression is `noexcept`, and optionally a return-type requirement: `-> C<Args...>` means `C<decltype((e)), Args...>` is satisfied. A **nested** requirement is the only one that checks a value: `requires E;` evaluates the constant expression `E`.

> **Pitfall.** A simple requirement checks that an expression compiles, not that it is true. `requires { sizeof(T) > 4; }` is satisfied by `char`, because `sizeof(char) > 4` is a perfectly valid expression whose value is `false`. To test the value, write a nested requirement, `requires { requires sizeof(T) > 4; }`, or just the expression `sizeof(T) > 4` itself.

Compound requirements see the expression's value category through `decltype((e))`. For `struct P { int x; }`, the requirement `{ p.x } -> std::same_as<int>` is not satisfied, because `p.x` is an lvalue and the type checked is `int&`. Use `std::convertible_to<int>` or `std::same_as<int&>` depending on what you mean.

Because a requires-expression is an expression, it can appear directly in a requires-clause, which produces the doubled keyword `requires requires`. The first introduces the clause, the second begins the expression. It is fine for a one-off check; give the condition a name once it appears twice.

```cpp
template <class T>
  requires requires(T a) { a + a; }
T twice(T a) { return a + a; }
```

## Atomic constraints and normalization

Normalization rewrites a constraint into conjunctions and disjunctions of atomic constraints. Only `&&` and `||` at the top level of a constraint expression, possibly inside parentheses, are logical operators here. A concept-id is replaced by its definition, with arguments substituted into it. Every other expression is an atom, and that includes `!C<T>`, `C<T> == true`, and `bool(A<T> && B<T>)`.

Each atom is checked by substituting the template arguments. If substitution produces an invalid type or expression, the atom is not satisfied, which is how a disjunction like `std::is_integral_v<T> || (T::value > 0)` works for `int`: the left side is true, so the right side is never substituted. If substitution succeeds, the expression must be a constant expression of type exactly `bool`. No conversion is applied, so `requires (T::value)` with an `int` member is not merely unsatisfied; the program is ill-formed.

> **Standardese.** [temp.constr.atomic] says an atomic constraint whose substitution fails is not satisfied, that a successful substitution must yield a constant expression of type `bool`, and that if the satisfaction result for identical atomic constraints and arguments differs at different points in the program, the program is ill-formed, no diagnostic required. Declaring a function that a requires-expression looks for, after the concept was already checked, falls into that last trap.

## Subsumption and overload ordering

When overload resolution cannot otherwise choose between two function templates with equivalent template parameter lists and parameter types, it prefers the more constrained one. Constraint P subsumes Q if, after normalization, every way of making P true also makes Q true, judged atom by atom. The standard library's concepts are built for this: `std::signed_integral<T>` is defined as `std::integral<T> && std::is_signed_v<T>`, so it subsumes `std::integral<T>`.

```cpp
#include <concepts>
#include <cstdio>

template <std::integral T> void f(T) { std::puts("integral"); }
template <std::signed_integral T> void f(T) { std::puts("signed_integral"); }

void demo() {
  f(1);   // signed_integral: both viable, the second subsumes the first
  f(1u);  // integral: the second is not satisfied
}
```

Identity is the whole game. Two atoms are identical only if they are the same expression *in the source* and their arguments map identically. Writing the same text twice in two different concepts creates two different atoms.

```cpp
#include <type_traits>

template <class T> concept Integral = std::is_integral_v<T>;
template <class T> concept Int32bad = std::is_integral_v<T> && sizeof(T) == 4;
template <class T> concept Int32 = Integral<T> && sizeof(T) == 4;

template <Integral T> int g(T) { return 1; }
template <Int32 T> int g(T) { return 2; }
// With Int32bad in place of Int32, g(0) would be ambiguous: its
// is_integral_v<T> atom is a different atom from Integral's.
```

The same reasoning explains why negation is awkward. `!Integral<T>` is a single opaque atom, not "the negation of `Integral`", so it never takes part in implication with `Integral<T>`. Mutually exclusive overloads written as `requires C<T>` and `requires (!C<T>)` work because only one is ever satisfied, not because either subsumes the other.

## Constrained auto and abbreviated templates

A placeholder can carry a type-constraint, and C++20 lets function parameters use placeholders, which makes the function an abbreviated function template. Each `auto` parameter invents its own template parameter, so `void f(auto a, auto b)` accepts two unrelated types.

```cpp
#include <concepts>

void take(std::convertible_to<long> auto x);  // means: template <class T>
                                              // requires std::convertible_to<T, long>
void use() {
  std::integral auto n = 2;          // deduce int, then check std::integral<int>
  // std::integral auto m = 2.0;     // error: deduced double does not satisfy it
  (void)n;
}
```

The deduced type is always inserted as the *first* argument of the concept, so `std::convertible_to<long> auto` checks `std::convertible_to<T, long>`. The same constrained placeholder works for variables, return types and `decltype(auto)`, where deduction happens first and the constraint is checked on the result.

## Satisfaction is not modelling

The compiler can only check syntax and constant expressions. Most standard concepts also carry semantic requirements: `std::equality_comparable` requires `==` to be an equivalence relation, `std::regular` requires copies to compare equal to the original, and many concepts require their expressions to be equality-preserving. A type *satisfies* a concept when the constraint evaluates to true. It *models* the concept when it also meets the semantic requirements.

> **Standardese.** [res.on.requirements] says that if the validity or meaning of a program depends on whether template arguments model a library concept, and the concept is satisfied but not modelled, the program is ill-formed, no diagnostic required. Passing a type whose `operator==` is not reflexive to `std::ranges::find` compiles and is still wrong.

This is also why concepts are not a substitute for reading a template's requirements: a constraint is the checkable shadow of a contract, not the contract. The SFINAE topic covers the older mechanism that constraints replace, and partial-ordering-of-templates covers how constraints act as the final tiebreaker after ordinary partial ordering.

## What to remember

- A concept is a named constraint; a concept-id is a `bool` prvalue. Concepts cannot be constrained, specialized or recursive.
- A requires-clause takes primary expressions joined by `&&` and `||`; parenthesize anything else.
- Simple, type and compound requirements check validity; only a nested `requires E;` checks a value.
- `{ e } -> C<Args...>` checks `C<decltype((e)), Args...>`, so a member access yields a reference type.
- Normalization splits on top-level `&&` and `||`; everything else, including `!C<T>`, is an opaque atom.
- An atom whose substitution fails is unsatisfied; an atom that is not exactly `bool` makes the program ill-formed.
- Atoms are identical only when they come from the same source expression, so build concepts out of other concepts if you want subsumption.
- Each `auto` parameter is its own template parameter, and a constrained placeholder puts the deduced type first.
- Satisfying a concept is syntax; modelling it adds semantics, and relying on an unmodelled concept is ill-formed, no diagnostic required.

## Concept Map Outline

- **Concepts and constraints:** Constraints are checked by evaluation after deduction and ordered by the structure of their atomic constraints.
  - **Concepts:** A concept is a named constraint; a concept-id is a prvalue of type bool.
    - **Restrictions:** A concept cannot be constrained, specialized, or refer to itself.
    - **Four spellings:** Type-constraint, requires-clause, trailing requires-clause, constrained auto.
    - **Clause grammar:** Operands are primary expressions; requires (sizeof(T) > 4) needs the parentheses.
  - **Requires-expressions:** A bool prvalue that is true when every requirement in its body is valid.
    - **Simple:** Checks that an expression is valid, never that it is true.
    - **Type:** typename X; checks that the type can be named.
    - **Compound:** { e } noexcept -> C checks C<decltype((e))>, so lvalues give reference types.
    - **Nested:** requires E; is the only requirement that evaluates a value.
    - **requires requires:** A clause whose operand is an ad hoc requires-expression.
  - **Atomic constraints:** Normalization splits on top-level && and ||; everything else is an opaque atom.
    - **Substitution failure:** An atom whose substitution is invalid is simply not satisfied.
    - **Exactly bool:** An atom of type int makes the program ill-formed; no conversion applies.
    - **Short-circuit:** In A || B, B is not substituted when A is satisfied.
    - **Stable results:** Satisfaction changing between points in the program is IFNDR.
  - **Subsumption:** The more constrained of two otherwise equivalent templates wins overload resolution.
    - **Atom identity:** Atoms match only if they come from the same source expression.
    - **Build on concepts:** Define Int32 as Integral<T> && ... so it subsumes Integral.
    - **Negation is opaque:** !C<T> is one atom and never implies or contradicts C<T>.
  - **Constrained auto:** A placeholder with a type-constraint deduces first, then checks the concept.
    - **Abbreviated templates:** Each auto parameter invents its own template parameter.
    - **Deduced type first:** C<int> auto checks C<T, int>, with the deduced type as the first argument.
  - **Satisfy vs model:** Satisfaction is syntax; modelling adds the concept's semantic requirements.
    - **IFNDR:** Relying on a library concept that is satisfied but not modelled is ill-formed, NDR.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.prim.req.simple], [expr.prim.req.nested])

What does this program print?

```cpp
#include <cstdio>

template <class T>
concept Big = requires { sizeof(T) > 4; };

int main() { std::printf("%d\n", Big<char>); }
```

A. `0`
B. `1`
C. Nothing: ill-formed, a requires-expression needs a parameter list
D. Nothing: ill-formed, `sizeof(T) > 4` is not a requirement

**Answer (B):** `1`

**Why:** `sizeof(T) > 4;` is a simple requirement, which only checks that the expression is valid. For `char` it is valid and evaluates to `false`, but the value is never looked at, so `Big<char>` is `true`. To test the value, write a nested requirement `requires sizeof(T) > 4;` inside the braces, or define the concept as `sizeof(T) > 4` directly. The parameter list of a requires-expression is optional.

### Question 2 [warmup] ([temp.pre], [temp.constr.decl])

Is this declaration well-formed?

```cpp
template <class T>
  requires sizeof(T) > 4
void f(T) {}
```

A. Well-formed: `f` accepts types larger than four bytes
B. Well-formed, but the constraint is always satisfied
C. Ill-formed: a constraint must be a concept-id
D. Ill-formed: `sizeof(T) > 4` must be parenthesized in a requires-clause

**Answer (D):** Ill-formed: `sizeof(T) > 4` must be parenthesized in a requires-clause

**Why:** The operands of a requires-clause must be primary expressions joined by `&&` or `||`. `sizeof(T)` is not a primary expression, so it cannot be the clause's operand and the declaration is ill-formed. Writing `requires (sizeof(T) > 4)` makes the whole comparison a parenthesized primary expression. Constraints are not limited to concept-ids; any constant `bool` expression works once it is parenthesized.

### Question 3 [warmup] ([temp.constr.order], [temp.func.order], [concepts.arithmetic])

What does this program print?

```cpp
#include <concepts>
#include <cstdio>

template <std::integral T> void f(T) { std::puts("integral"); }
template <std::signed_integral T> void f(T) { std::puts("signed_integral"); }

int main() { f(1); f(1u); }
```

A. `signed_integral` then `integral`
B. Nothing: the call `f(1)` is ambiguous
C. `integral` then `integral`
D. `signed_integral` then nothing: `f(1u)` is ill-formed

**Answer (A):** `signed_integral` then `integral`

**Why:** For `f(1)` both templates are viable with identical parameter types, so the more constrained one wins. `std::signed_integral<T>` is defined as `std::integral<T> && std::is_signed_v<T>`, which normalizes to a conjunction containing the very same atom as `std::integral`, so it subsumes it. For `f(1u)` only the first template is satisfied. Ambiguity would arise only if the two concepts were written independently.

### Question 4 [tricky] ([temp.constr.order], [temp.constr.atomic], [temp.constr.normal])

Is the call `g(0)` well-formed?

```cpp
#include <type_traits>

template <class T> concept Integral = std::is_integral_v<T>;
template <class T> concept Int32 = std::is_integral_v<T> && sizeof(T) == 4;

template <Integral T> int g(T) { return 1; }
template <Int32 T> int g(T) { return 2; }

int main() { return g(0); }
```

A. Well-formed: it calls the `Int32` overload, which has more requirements
B. Ill-formed: the call is ambiguous
C. Well-formed: it calls the `Integral` overload, which was declared first
D. Ill-formed, no diagnostic required

**Answer (B):** Ill-formed: the call is ambiguous

**Why:** Subsumption compares atomic constraints by identity, and two atoms are identical only if they come from the same expression in the source. The `std::is_integral_v<T>` in `Int32` is a different atom from the one in `Integral`, so neither constraint subsumes the other and the call is ambiguous. Defining `Int32` as `Integral<T> && sizeof(T) == 4` makes the `Int32` overload win.

### Question 5 [tricky] ([expr.prim.req.compound], [dcl.type.decltype])

What does this program print?

```cpp
#include <concepts>
#include <cstdio>

template <class T>
concept HasIntX = requires(T t) { { t.x } -> std::same_as<int>; };

struct P { int x; };

int main() { std::printf("%d\n", HasIntX<P>); }
```

A. `1`
B. Nothing: ill-formed, `t` cannot be used in a compound requirement
C. `0`
D. It depends on whether `P` is an aggregate

**Answer (C):** `0`

**Why:** A return-type requirement `-> C` checks `C<decltype((e))>`, with the doubled parentheses. `t.x` is an lvalue, so `decltype((t.x))` is `int&`, and `std::same_as<int&, int>` is false. Reading it as `decltype(t.x)`, which would be `int`, is what makes `1` tempting. Use `std::same_as<int&>` or `std::convertible_to<int>` instead.

### Question 6 [tricky] ([temp.constr.atomic])

What happens when this program is compiled?

```cpp
template <class T> requires (T::value) int f() { return 0; }
template <class T> int f() { return 1; }

struct S { static constexpr int value = 1; };

int main() { return f<S>(); }
```

A. It compiles and `main` returns 0: `1` converts to `true`
B. It compiles and `main` returns 1: the constraint is not satisfied
C. Ill-formed: the call is ambiguous
D. Ill-formed: the atomic constraint `T::value` has type `int`, not `bool`

**Answer (D):** Ill-formed: the atomic constraint `T::value` has type `int`, not `bool`

**Why:** Substitution into the atom `T::value` succeeds, so the result must be a constant expression of type exactly `bool`; no conversion is applied, and an `int` makes the program ill-formed rather than leaving the constraint unsatisfied. The "not satisfied" reading applies only when substitution itself fails, for example if `S` had no `value` at all. Writing `requires (T::value != 0)` or `requires bool(T::value)` fixes it.

### Question 7 [standardese] ([temp.constr.atomic])

What does the C++23 standard say about this translation unit?

```cpp
template <class T> concept HasFoo = requires(T t) { foo(t); };

struct S {};
static_assert(!HasFoo<S>);

void foo(S);
static_assert(HasFoo<S>);
```

A. Both assertions pass, since `foo` is found by the time of the second
B. Ill-formed, no diagnostic required
C. The second assertion must fail, because concept results are cached
D. Ill-formed: `foo` must be declared before the concept

**Answer (B):** Ill-formed, no diagnostic required

**Why:** The atomic constraint `requires(T t) { foo(t); }` with `T = S` is false at the first assertion and would be true at the second. [temp.constr.atomic] makes a program ill-formed, no diagnostic required, when identical atomic constraints with identical arguments have different satisfaction results at different points. GCC and Clang both remember the first result and fail the second assertion, which is why the third option is tempting, but the standard does not require that.

### Question 8 [standardese] ([res.on.requirements], [concept.equalitycomparable])

What does the C++23 standard say about this program?

```cpp
#include <algorithm>
#include <vector>

struct Odd {
  int v;
  bool operator==(const Odd&) const { return false; }
};

int main() {
  std::vector<Odd> xs{{1}, {2}};
  auto it = std::ranges::find(xs, Odd{1});
  return it == xs.end();
}
```

A. Well-formed: `main` returns 1
B. Ill-formed: `Odd` does not satisfy `std::equality_comparable`
C. Undefined behavior
D. Ill-formed, no diagnostic required

**Answer (D):** Ill-formed, no diagnostic required

**Why:** `Odd` satisfies the syntactic part of `std::equality_comparable`, so the call compiles, but it does not model the concept, whose semantic requirements make `==` an equivalence relation and `a == a` true. [res.on.requirements] says a program whose validity or meaning depends on a concept being modelled, when it is only satisfied, is ill-formed, no diagnostic required. Returning 1 is what you will probably observe, which is exactly why the rule is easy to miss.

# Forwarding References and Perfect Forwarding

> Decode the T&& template deduction exception, reference collapsing rules, and why std::forward and C++23 std::forward_like preserve exact value category and constness.

- **Source:** C++ Atlas (https://cppatlas.com/topics/forwarding-references-and-perfect-forwarding)
- **Track:** Templates
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [dcl.ref] (https://eel.is/c++draft/dcl.ref), [dcl.init.ref] (https://eel.is/c++draft/dcl.init.ref), [temp.deduct.call] (https://eel.is/c++draft/temp.deduct.call), [dcl.type.auto.deduct] (https://eel.is/c++draft/dcl.type.auto.deduct), [forward] (https://eel.is/c++draft/forward), [temp.variadic] (https://eel.is/c++draft/temp.variadic)
- **cppreference links:** [Template argument deduction](https://en.cppreference.com/w/cpp/language/template_argument_deduction), [Reference declaration](https://en.cppreference.com/w/cpp/language/reference), [Reference initialization](https://en.cppreference.com/w/cpp/language/reference_initialization), [std::forward](https://en.cppreference.com/w/cpp/utility/forward), [std::forward_like](https://en.cppreference.com/w/cpp/utility/forward_like), [std::move](https://en.cppreference.com/w/cpp/utility/move), [Placeholder type specifiers](https://en.cppreference.com/w/cpp/language/auto)
- **Prerequisites:** value-categories, type-deduction-auto-decltype, reference-binding-and-temporaries

Generic factories, wrappers, and `emplace` methods must pass arguments along to an inner constructor or function without copying lvalues or blocking moves on rvalues. Perfect forwarding achieves that by encoding the caller's value category inside a deduced template type parameter and restoring it at the forwarding boundary.

## When T&& is a forwarding reference (and when it isn't)

Despite sharing syntax with rvalue references, `T&&` becomes a **forwarding reference** (colloquially called a universal reference) only under an exact syntactic condition (`[temp.deduct.call]`): `T` must be a cv-unqualified template type parameter **of that specific function template**, written directly in the form `T&&` (or `auto&&` in variable declarations and generic lambda parameters).

Any cv-qualifier, wrapper type, or enclosing class-template parameter turns `&&` back into a strict rvalue reference that rejects lvalues:

```cpp
#include <vector>

template <class T>
void relay(T&& arg);                // forwarding reference: T is deduced here

template <class T>
void fixed(const T&& arg);          // plain rvalue reference: const disqualifies it

template <class T>
void wrap(std::vector<T>&& arg);    // plain rvalue reference: not bare T&&

template <class T>
struct Box {
    void push(T&& item);            // plain rvalue reference: T comes from Box<T>!
    template <class... Args>
    void emplace(Args&&... args);   // forwarding reference pack: Args deduced per call
};
```

> **Pitfall.** Writing `void push(T&&)` inside `template <class T> struct Box` does **not** declare a forwarding reference. By the time `push` is called on a `Box<Widget>`, `T` is already fixed to `Widget`, so `push` accepts only rvalues. Only a member function template with its own deduced parameter (`Args&&...`) forwards both lvalues and rvalues.

## The deduction exception and reference collapsing

Ordinarily, template argument deduction strips top-level references from parameter patterns. Forwarding references receive a deliberate exception in `[temp.deduct.call]`:

- When the call argument is an **lvalue** of type `U`, `T` is deduced as an **lvalue reference `U&`**.
- When the call argument is an **rvalue** (prvalue or xvalue) of type `U`, `T` is deduced as the non-reference type **`U`**.

C++ forbids writing a reference-to-reference directly in source (`int& &`), yet template substitution, type aliases, and `decltype` routinely produce them. Under `[dcl.ref]`, **reference collapsing** reduces every reference-to-reference pair by one rule: lvalue reference `&` is infectious. Combining `&` with `&`, `&` with `&&`, or `&&` with `&` yields `&`; only `&&` combined with `&&` remains `&&`.

| Call argument | Value category | Deduced `T` | Parameter `T&&` | `std::forward<T>(arg)` |
| --- | --- | --- | --- | --- |
| `Widget w;` | lvalue | `Widget&` | `Widget&` | `Widget&` (lvalue) |
| `const Widget cw;` | const lvalue | `const Widget&` | `const Widget&` | `const Widget&` (lvalue) |
| `Widget{}` | prvalue | `Widget` | `Widget&&` | `Widget&&` (xvalue) |
| `std::move(w)` | xvalue | `Widget` | `Widget&&` | `Widget&&` (xvalue) |

> **Mental model.** A forwarding reference uses `T` as a single-bit envelope recording whether the caller supplied an lvalue (`T = U&`) or an rvalue (`T = U`). Reference collapsing turns `T&&` into the exact parameter type needed to bind either one without copying.

## How std::forward and std::forward_like work

Inside `relay(T&& arg)`, the parameter `arg` has a name. Regardless of whether `arg` was bound to an lvalue or an rvalue, the expression `arg` inside the body is **always an lvalue**. Passing `arg` directly to another function would therefore invoke its copy overload even when the caller passed a temporary.

`std::forward<T>(arg)` unpacks the envelope stored in `T` by computing `static_cast<T&&>(arg)`:

- If the caller passed an lvalue, `T` is `Widget&`, so `static_cast<Widget& &&>(arg)` collapses to `static_cast<Widget&>(arg)`—an lvalue.
- If the caller passed an rvalue, `T` is `Widget`, so `static_cast<Widget&&>(arg)` casts the named lvalue back into an xvalue, enabling moves.

Notice why you must always supply `<T>` explicitly (`std::forward<T>(arg)`): `std::forward`'s parameter uses `std::remove_reference_t<T>&` (a non-deduced context) specifically so deduction cannot look at `arg`—which is always an lvalue—and erase the caller's value category. Furthermore, `[forward]` includes a second overload taking `remove_reference_t<T>&&` with a mandated static check ensuring `!std::is_lvalue_reference_v<T>`, so `std::forward<Widget&>(Widget{})` is rejected at compile time rather than returning a dangling lvalue reference to a temporary.

When forwarding a **member or subobject** of a forwarded aggregate `Self&& owner`, C++23 adds `std::forward_like<Self>(owner.member)`. Simply writing `std::forward<Self>(owner).member` fails to move if `member` is a reference or if `Self`'s cv-qualification and value category must be merged onto `member` cleanly:

```cpp
#include <string>
#include <utility>

struct Holder {
    std::string& ref;
};

template <class Self>
decltype(auto) extract(Self&& owner) {
    // Merges Self's constness and value category onto owner.ref
    return std::forward_like<Self>(owner.ref);
}
```

If `owner` is a `Holder&&`, `extract` yields `std::string&&`; if `owner` is `const Holder&&`, it yields `const std::string&&`; if `owner` is `const Holder&`, it yields `const std::string&`.

## Variadic forwarding and universal traps

Real factory wrappers combine forwarding references with parameter packs (`template <class... Args> auto make(Args&&... args) { return Target(std::forward<Args>(args)...); }`). Three sharp pitfalls arise in practice:

1. **Greedy forwarding constructors:** A single-argument template constructor `template <class S> Person(S&& name)` beats `Person(const Person&)` whenever you copy-construct from a **non-const** lvalue `Person p1; Person p2(p1);`. `S` deduces to `Person&` (an exact match), whereas `Person(const Person&)` requires adding `const`. Guard forwarding constructors with concepts (`requires (!std::same_as<std::remove_cvref_t<S>, Person>)`).
2. **Non-deduced braced-init-lists:** Calling `relay({1, 2, 3})` fails to deduce `T`. Unlike `auto x = {1, 2, 3};` (which has a special rule deducing `std::initializer_list<int>`), a braced-init-list is a non-deduced context for template parameter `T` (`[temp.deduct.call]`).
3. **Double forwarding:** Never call `std::forward<T>(arg)` twice on the same parameter in sequence. The first forwarded call may steal `arg`'s resources when the caller passed an rvalue, leaving the second call reading a moved-from object.

> **Standardese.** Under `[temp.deduct.call]`, a braced-init-list `{...}` matches a function template parameter only if that parameter explicitly names `std::initializer_list<U>` or an array/aggregate pattern—never a bare forwarding parameter `T&&`.

## What to remember

- `T&&` is a forwarding reference only when `T` is a cv-unqualified template parameter deduced by that exact function template (or `auto&&`), never `const T&&`, `Vec<T>&&`, or a class template's `T&&`.
- Lvalues deduce `T = U&` and rvalues deduce `T = U`; reference collapsing makes `&` win over `&&` in every combination.
- Named parameters are always lvalues; `std::forward<T>(arg)` restores xvalue-ness only when `T` is non-reference, and rejects forwarding an rvalue as an lvalue reference.
- Use C++23 `std::forward_like<Self>(member)` when forwarding a member or reference field according to its owner's constness and value category.
- Constrain single-argument forwarding constructors so they do not hijack non-const lvalue copies, and remember braced `{...}` arguments cannot deduce `T`.

## Concept Map Outline

- **Forwarding References:** Perfect forwarding encodes the caller's value category into a deduced type T and unpacks it with std::forward.
  - **Syntactic Conditions:** Only bare cv-unqualified T&& deduced at that function call acts as a forwarding reference.
    - **Deduced Function T&&:** T must be a template parameter of the function itself written directly as T&&.
    - **auto&& Variables & Lambdas:** auto&& obeys the exact same template deduction and collapsing rules for variables and generic lambdas.
    - **Disqualified Forms:** const T&&, vector<T>&&, and class-template Box<T>::push(T&&) are plain rvalue references.
  - **Deduction & Collapsing:** A special deduction rule pairs with reference collapsing to bind both lvalues and rvalues.
    - **Lvalue Deduces T&:** Passing an lvalue U deduces T as U&, making T&& collapse to U&.
    - **Rvalue Deduces T:** Passing a prvalue or xvalue U deduces T as U, leaving T&& as U&&.
    - **Infectious Lvalue Collapse:** Any reference-to-reference containing & collapses to &; only && plus && stays &&.
  - **Forwarding Mechanics:** Named parameters become lvalues inside bodies and must be cast back selectively.
    - **Named Param Is Lvalue:** Every named function parameter—even typed Widget&&—acts as an lvalue expression inside the body.
    - **std::forward Cast:** std::forward<T>(arg) performs static_cast<T&&>(arg) and forbids turning rvalues into lvalue refs.
    - **C++23 forward_like:** std::forward_like<Self>(member) transfers Self's constness and value category onto a subobject or ref.
  - **Variadic Forwarding:** Parameter packs forward arbitrary argument lists intact into constructors and factories.
    - **Pack Expansion:** Writing std::forward<Args>(args)... forwards every argument with its independent value category.
    - **Non-Deduced Braces:** Braced initializer lists like {1, 2} cannot deduce T&& and fail template deduction.
  - **Common Traps:** Unconstrained forwarding signatures silently steal copies or introduce double-move bugs.
    - **Greedy Copy Hijack:** An unconstrained T&& constructor beats const T& when copying a non-const lvalue.
    - **Double Forward Bug:** Forwarding the same parameter twice can read from an already moved-from rvalue.
    - **Dangling Forwarded Ref:** Returning a forwarded rvalue reference from a local temporary creates immediate dangling.

## Standardese Quiz Questions

### Question 1 [warmup] ([temp.deduct.call])

Which parameter declaration actually behaves as a forwarding reference capable of binding both lvalues and rvalues?

A. template <class T> void f(const T&& x);
B. template <class T> void f(std::vector<T>&& x);
C. template <class T> struct Holder { void put(T&& x); };
D. template <class T> void f(T&& x);

**Answer (D):** template <class T> void f(T&& x);

**Why:** Under [temp.deduct.call], T&& is a forwarding reference only when T is a cv-unqualified template parameter deduced for that exact function call. Adding const, wrapping in vector<T>, or using an enclosing class template's T produces a plain rvalue reference.

### Question 2 [warmup] ([temp.deduct.call], [dcl.ref])

Given `template <class T> void relay(T&& arg)` called with `int count = 7; relay(count);`, what are T, the declared type of arg, and the value category of expression `arg` inside relay?

A. T is int&, arg has type int&, and expression arg is an lvalue
B. T is int, arg has type int&&, and expression arg is an xvalue
C. T is int&, arg has type int&&, and expression arg is an lvalue
D. T is int, arg has type int&, and expression arg is a prvalue

**Answer (A):** T is int&, arg has type int&, and expression arg is an lvalue

**Why:** Passing an lvalue `count` deduces T = int& ([temp.deduct.call]). Reference collapsing turns T&& (int& &&) into int& ([dcl.ref]), and as a named variable `arg` is an lvalue.

### Question 3 [tricky] ([over.match.best], [temp.deduct.call])

Why does constructing `p2` from non-const `p1` fail to compile (or select the wrong constructor) below?

```cpp
struct Person {
    std::string name;
    template <class S>
    explicit Person(S&& s) : name(std::forward<S>(s)) {}
    Person(const Person& other) = default;
};
Person p1{"Ada"};
Person p2(p1);
```

A. Defaulted copy constructors cannot coexist with template constructors
B. Person(S&&) is explicit while copy construction requires an implicit constructor
C. The template constructor deduces S = Person&, which is an exact match that beats Person(const Person&)'s qualification conversion
D. std::forward<Person&>(p1) returns a moved-from Person

**Answer (C):** The template constructor deduces S = Person&, which is an exact match that beats Person(const Person&)'s qualification conversion

**Why:** Because `p1` is a non-const `Person` lvalue, `Person(S&&)` instantiates `Person(Person&)`, which requires no `const` qualification conversion and beats `Person(const Person&)` in overload resolution—then fails trying to construct `std::string` from `Person&`.

### Question 4 [tricky] ([temp.deduct.call])

What happens when calling `forward_to_vec({1, 2, 3})` where `forward_to_vec` takes `T&&`?

```cpp
void take_vec(std::vector<int> v);
template <class T>
void forward_to_vec(T&& arg) {
    take_vec(std::forward<T>(arg));
}
// forward_to_vec({1, 2, 3});
```

A. T deduces to std::initializer_list<int>, constructing std::vector<int>
B. Compilation fails because a braced-init-list is a non-deduced context for T&&
C. T deduces to int[3] and converts to std::vector<int>
D. Compiles only if T&& is replaced with const T&

**Answer (B):** Compilation fails because a braced-init-list is a non-deduced context for T&&

**Why:** Unlike `auto x = {1, 2, 3};`, template deduction against a bare `T&&` parameter cannot deduce `std::initializer_list` from a braced-init-list ({...} is a non-deduced context under [temp.deduct.call]).

### Question 5 [standardese] ([forward], [temp.deduct.type])

Why does `std::forward<T>(arg)` use `std::remove_reference_t<T>&` in its parameter instead of deducing `T` from `arg` automatically?

A. Inside the forwarding function, `arg` is always an lvalue; deducing T from `arg` would always yield an lvalue reference and lose whether the caller passed an rvalue
B. Template parameters can never be deduced for functions inside namespace std
C. std::remove_reference_t<T>& prevents std::forward from accepting const objects
D. Automatic deduction would trigger copy elision on `arg`

**Answer (A):** Inside the forwarding function, `arg` is always an lvalue; deducing T from `arg` would always yield an lvalue reference and lose whether the caller passed an rvalue

**Why:** By placing `T` inside the non-deduced type `std::remove_reference_t<T>&`, `[forward]` forces callers to pass the outer deduced `T` explicitly—preserving the distinction between `T = U&` (caller gave lvalue) and `T = U` (caller gave rvalue).

### Question 6 [standardese] ([forward])

What does the C++ standard specify for `std::forward<int&>(42)`?

```cpp
int& bad() {
    return std::forward<int&>(42);
}
```

A. Returns a dangling int& bound to temporary 42
B. Implicitly converts 42 into a static storage int so the reference stays valid
C. Ill-formed: the rvalue overload of std::forward mandates `!std::is_lvalue_reference_v<T>`
D. Returns an int prvalue by decaying the reference

**Answer (C):** Ill-formed: the rvalue overload of std::forward mandates `!std::is_lvalue_reference_v<T>`

**Why:** Under [forward], the overload `template<class T> constexpr T&& forward(remove_reference_t<T>&& t)` mandates that `is_lvalue_reference_v<T>` is `false`. Passing an rvalue (`42`) while requesting an lvalue-reference `T` (`int&`) is explicitly ill-formed.

# Class template argument deduction

> Since C++17 you can name a class template without arguments and let the initializer decide them. The compiler turns every constructor and deduction guide into a fictional function template, runs overload resolution against them, and uses the winner's return type; the surprises come from which fictional function wins.

- **Source:** C++ Atlas (https://cppatlas.com/topics/class-template-argument-deduction)
- **Track:** Templates
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [over.match.class.deduct] (https://eel.is/c++draft/over.match.class.deduct), [temp.deduct.guide] (https://eel.is/c++draft/temp.deduct.guide), [dcl.type.class.deduct] (https://eel.is/c++draft/dcl.type.class.deduct), [over.match.best] (https://eel.is/c++draft/over.match.best), [over.match.list] (https://eel.is/c++draft/over.match.list), [temp.deduct.call] (https://eel.is/c++draft/temp.deduct.call), [dcl.init.aggr] (https://eel.is/c++draft/dcl.init.aggr)
- **cppreference links:** [Class template argument deduction (CTAD)](https://en.cppreference.com/w/cpp/language/class_template_argument_deduction), [Deduction guides for std::vector](https://en.cppreference.com/w/cpp/container/vector/deduction_guides), [Deduction guides for std::pair](https://en.cppreference.com/w/cpp/utility/pair/deduction_guides), [Aggregate initialization](https://en.cppreference.com/w/cpp/language/aggregate_initialization)
- **Prerequisites:** template-argument-deduction, initialization-forms, overload-resolution

## The one idea

When a declaration names a class template without an argument list, as in `std::pair p(1, 2.0);`, the compiler has to invent the arguments. It does so with machinery you already know. Every constructor of the primary template, and every deduction guide, becomes a fictional function template whose return type is the class specialization it would produce. The initializer is treated as the argument list of a call to that overload set. Ordinary template argument deduction and overload resolution pick one candidate, and its return type is the type of the variable.

Only then does real initialization happen, using the real constructors of the deduced type. Deduction chooses a type; it does not choose the constructor that runs.

> **Mental model.** CTAD is overload resolution over a set of imaginary factory functions, one per constructor plus one per guide plus a copy candidate. If you can predict which imaginary factory wins, you can predict the type.

## Implicit guides from constructors

For each constructor of the primary template, [over.match.class.deduct] forms a function template whose template parameters are the class's parameters followed by the constructor's own, whose function parameters are the constructor's, and whose return type is the class specialization. Constructors of partial or explicit specializations are not used. If the class declares no constructors, a hypothetical default constructor is used instead, which is how `template <class T = int> struct X {}; X x;` deduces `X<int>`.

```cpp
template <class T>
struct Pt {
  T x, y;
  Pt(T a, T b) : x(a), y(b) {}   // implicit guide: template <class T> Pt(T, T) -> Pt<T>
};

Pt p(1, 2);         // Pt<int>
auto r = Pt(3, 4);  // functional cast: also Pt<int>
// Pt q(1, 2.0);    // error: T deduced as both int and double
```

Because the implicit guides take parameters by the same types as the constructors, they inherit the constructors' deduction behaviour. One rule is deliberately different: a constructor parameter `T&&` where `T` is a class template parameter is not a forwarding reference during CTAD. With `Holder(T&&)` as the only constructor, `Holder h(i);` for an lvalue `i` deduces `T = int` and then fails to bind `int&&` to `i`. The forwarding-references topic explains the rule this exclusion switches off.

## User-defined deduction guides

When constructors do not carry enough information, you write a guide. It looks like a function declaration with a trailing return type and the class template's name in place of a function name. It must be declared in the same scope as the class template, it has no body, and it can be a template or not.

```cpp
#include <iterator>
#include <string>
#include <vector>

template <class T> struct Bag {
  std::vector<T> items;
  template <class It> Bag(It b, It e) : items(b, e) {}  // T is not deducible from It
};
template <class It>
Bag(It, It) -> Bag<typename std::iterator_traits<It>::value_type>;

template <class T> struct Name { T value; Name(T v) : value(v) {} };
Name(const char*) -> Name<std::string>;  // non-template guide

void demo() {
  int a[] = {1, 2, 3};
  Bag b(a, a + 3);  // Bag<int>
  Name n("Ada");    // Name<std::string>, not Name<const char*>
}
```

The standard library uses exactly this: `std::vector` has an iterator-pair guide, and `std::pair` has `pair(T1, T2) -> pair<T1, T2>`. Its parameters are by value, so arguments decay: `std::pair p{1, "hi"}` is `std::pair<int, const char*>`, not a pair holding an array.

A guide is also the repair for the `Holder(T&&)` problem from the previous section. A guide's template parameters are its own, not the class's, so in `template <class U> Holder(U&&) -> Holder<std::remove_cvref_t<U>>;` the parameter is a genuine forwarding reference, and an lvalue `int` deduces `Holder<int>`. The constructor that then runs must still accept an lvalue, so such classes usually pair the guide with a constructor template.

A guide only names the result. If it names a type whose constructors cannot accept the initializer, deduction succeeds and initialization then fails, with an error that points at a constructor rather than at the guide.

> **Standardese.** [over.match.best] adds CTAD-specific tiebreakers that apply only after conversion sequences and partial ordering fail to separate two candidates: a candidate generated from a user-defined guide beats one generated from a constructor, the copy deduction candidate beats other constructor-generated candidates, and one generated from a non-template constructor beats one from a constructor template.

## The copy deduction candidate: copying beats wrapping

Besides constructors and guides, the set always contains a copy deduction candidate, built from a hypothetical constructor `C(C)`: in effect `template <class T> C(C<T>) -> C<T>`. Given an existing `std::vector<int> other`, both of these are candidates for `std::vector v{other};`:

```text
initializer_list ctor:  vector(initializer_list<T>)  ->  T = vector<int>   (wraps)
copy deduction:         vector(vector<T>)            ->  T = int           (copies)
```

List-initialization normally tries initializer-list constructors first, which would make `v` a `std::vector<std::vector<int>>` of one element. C++17, through P0702, added a rule to stop that: when the braced list consists of a single element whose type is a specialization of the class template, or a class derived from one, the initializer-list phase is skipped. The copy deduction candidate then wins, and `v` is a copy.

```cpp
#include <type_traits>
#include <vector>

void demo() {
  std::vector<int> other{1, 2, 3};
  std::vector v{other};         // std::vector<int>: a copy of other
  std::vector w{other, other};  // std::vector<std::vector<int>>: two elements
  static_assert(std::is_same_v<decltype(v), std::vector<int>>);
  static_assert(std::is_same_v<decltype(w), std::vector<std::vector<int>>>);
}
```

The same rule applies to `std::optional o{opt};` and `std::tuple t{tup};`, which copy rather than nest. Generic code that wraps whatever it is given, such as `std::vector v{x};` for an arbitrary `x`, changes meaning when `x` happens to be a vector. Spell the type out in generic code.

> **Pitfall.** Adding one element to a braced list flips the result from "copy" to "container of containers". Code that builds `std::vector{a}` and `std::vector{a, b}` from the same kind of value gets two unrelated element types.

## Braces, parentheses and initializer lists

Apart from the single-element rule, CTAD follows normal initialization: with braces, initializer-list constructors get first claim. That turns an innocent iterator pair into a vector of iterators.

```cpp
#include <string>
#include <type_traits>
#include <vector>

void demo() {
  std::string s = "hello";
  std::vector a(s.begin(), s.end());  // std::vector<char>, five elements
  std::vector b{s.begin(), s.end()};  // std::vector<std::string::iterator>, two elements
  std::vector c(3, 1);                // std::vector<int>{1, 1, 1}
  std::vector d{3, 1};                // std::vector<int>{3, 1}
  static_assert(std::is_same_v<decltype(b), std::vector<std::string::iterator>>);
}
```

`explicit` matters too. Guides generated from `explicit` constructors are explicit, a user-defined guide can be declared `explicit`. In copy-initialization without braces, explicit candidates are not considered at all; in copy-list-initialization they are considered, and choosing one makes the program ill-formed. With `explicit Box(const char*) -> Box<std::string>;`, the direct-initialization `Box a("hi");` gives `Box<std::string>`, but `Box b = "hi";` ignores the guide and deduces `Box<const char*>` from the constructor.

## Aggregates, aliases and inherited constructors

C++20 extended CTAD in two directions, and C++23 in a third.

**Aggregates (C++20).** An aggregate class template has no constructors to generate guides from. For an aggregate, the compiler now forms an aggregate deduction candidate whose parameters are the element types matched to the initializer's elements. It works for braced initialization and for C++20 parenthesized aggregate initialization.

```cpp
template <class T> struct Agg { T a; T b; };

Agg x{1, 2};      // Agg<int> in C++20; ill-formed in C++17 without a guide
Agg y(1, 2);      // also Agg<int>, via parenthesized aggregate initialization
// Agg z{1, 2.0}; // error: T deduced as both int and double
```

`std::array` predates this and keeps its own guide, which requires all elements to have the same type.

**Alias templates (C++20).** Naming an alias template without arguments now deduces too. The compiler takes the guides of the aliased class template, deduces the alias's parameters from each guide's return type, and keeps the guides for which that works. Given `template <class T> using Vec = std::vector<T>;`, the declaration `Vec v{1, 2, 3};` deduces `std::vector<int>`. GCC and Clang both implement this.

**Inherited constructors (C++23).** P2582 makes constructors inherited with a using-declaration contribute guides to the derived class template. Given `template <class T> struct Derived : Base<T> { using Base<T>::Base; };`, the declaration `Derived d(42);` deduces `Derived<int>` from `Base(T)`. GCC implements this from version 14; Clang 21 does not yet, so portable code still needs explicit guides.

## What CTAD will not do

CTAD is all or nothing. `std::pair<int> p{1, 2.0};` is not "deduce the second argument": once an argument list is present, no deduction happens, and a `pair` with one argument is simply wrong. `Foo<> f;` is also not CTAD; it explicitly asks for all defaults. If you want to fix some arguments and deduce others, write a factory function or an alias template that fixes them.

CTAD is also limited to certain declarations. [dcl.type.class.deduct] allows a deduced class type in a variable declaration with an initializer, a functional cast, a `new` expression, and, since C++20, the type of a non-type template parameter. It is not allowed for non-static data members, even with a default member initializer, nor for function parameters or return types.

```cpp
#include <vector>

struct S {
  // std::vector v{1, 2};   // error: no CTAD for non-static data members
  std::vector<int> v{1, 2};
};
```

## What to remember

- CTAD is overload resolution over fictional functions: one per constructor of the primary template, one per guide, plus the copy deduction candidate.
- The winner only chooses the type; the real constructors of that type then perform initialization.
- A class template's `T&&` constructor parameter is not a forwarding reference during CTAD.
- Guides have no body, live in the class template's scope, may be non-templates, and may be `explicit`; `T x = init;` ignores explicit guides, and `T x = {init};` is ill-formed if one wins.
- A braced list with one element of the same template's type copies; `std::vector v{other}` is a copy, `std::vector v{other, other}` nests.
- With braces, initializer-list constructors win, so `std::vector{s.begin(), s.end()}` holds two iterators.
- C++20 added aggregate CTAD and alias template CTAD; C++23 added inherited constructors, which Clang 21 does not implement.
- No partial deduction, and no CTAD for data members or function parameters.

## Concept Map Outline

- **CTAD:** Overload resolution over fictional functions built from constructors and guides picks the class's template arguments.
  - **Implicit guides:** Each constructor of the primary template becomes a function template returning C<T...>.
    - **Primary template only:** Constructors of partial or explicit specializations are never used.
    - **No constructors:** A hypothetical C() is used, so default template arguments can deduce.
    - **T&& is not forwarding:** A class parameter's T&& in a constructor does not forward during CTAD.
    - **Type, not constructor:** The winner chooses the type; real constructors then initialize it.
  - **User-defined guides:** Declarations like Bag(It, It) -> Bag<value_type>, with no body.
    - **Same scope:** A guide must be declared in the scope of its class template.
    - **Non-template guides:** Name(const char*) -> Name<std::string> needs no template head.
    - **By-value decay:** pair(T1, T2) decays arrays, so pair{1, "hi"} holds const char*.
    - **Guides win ties:** After partial ordering, a user guide beats a constructor-generated candidate.
  - **Copy deduction:** A candidate from a hypothetical C(C) is always added to the set.
    - **Single element copies:** A one-element braced list of a C specialization skips the initializer-list phase.
    - **Two elements nest:** std::vector v{other, other} is a vector of vectors.
    - **Generic code trap:** std::vector{x} copies when x is a vector and wraps otherwise.
  - **Braces and explicit:** CTAD follows ordinary initialization rules once the candidates are formed.
    - **Iterator pairs:** std::vector{b, e} holds two iterators; std::vector(b, e) holds the elements.
    - **Explicit guides:** Ignored in T x = init; selecting one in T x = {init} is ill-formed.
  - **Later extensions:** C++20 and C++23 widened where guides come from.
    - **Aggregates (C++20):** An aggregate deduction candidate works with braces and parentheses.
    - **Alias templates (C++20):** The aliased template's guides are adapted to the alias's parameters.
    - **Inherited ctors (C++23):** P2582: using Base<T>::Base contributes guides; GCC 14+, not Clang 21.
  - **Limits:** Where and how much CTAD can deduce.
    - **All or nothing:** pair<int> p{1, 2.0} is an invalid template-id, not partial deduction.
    - **Allowed places:** Variables with initializers, functional casts, new, and C++20 NTTP types.
    - **Not allowed:** Non-static data members, function parameters and return types.

## Standardese Quiz Questions

### Question 1 [warmup] ([over.match.class.deduct], [over.match.list])

What does this program print?

```cpp
#include <cstdio>
#include <vector>

int main() {
  std::vector<int> other{1, 2, 3};
  std::vector v{other};
  std::printf("%zu\n", v.size());
}
```

A. `1`, because `v` is a `std::vector<std::vector<int>>`
B. `3`
C. Nothing: ill-formed, the deduction is ambiguous
D. `0`

**Answer (B):** `3`

**Why:** When a braced list has a single element whose type is a specialization of the class template being deduced, the initializer-list phase is skipped, so the copy deduction candidate `vector(vector<T>) -> vector<T>` wins with `T = int`. `v` is a copy of `other` with three elements. Wrapping was the result before P0702 fixed it for C++17, and it is what you get with two elements, `std::vector v{other, other}`.

### Question 2 [warmup] ([pairs.pair], [temp.deduct.call], [over.match.class.deduct])

What is the type of `p.second`?

```cpp
#include <utility>

std::pair p{1, "hi"};
```

A. `const char[3]`
B. `std::string`
C. `const char (&)[3]`
D. `const char*`

**Answer (D):** `const char*`

**Why:** `std::pair` has the deduction guide `pair(T1, T2) -> pair<T1, T2>`, which takes its parameters by value. Deducing a by-value parameter from an array argument decays it, so `T2` is `const char*` and `p` is `std::pair<int, const char*>`. An array type is tempting because the constructor taking `const T2&` would preserve it, but the guide is what decides the type here.

### Question 3 [warmup] ([dcl.type.class.deduct], [temp.arg])

Is this declaration well-formed?

```cpp
#include <utility>

std::pair<int> p{1, 2.0};
```

A. Ill-formed: `std::pair` needs two template arguments, and CTAD is all or nothing
B. Well-formed: `p` is `std::pair<int, double>`
C. Well-formed: `p` is `std::pair<int, int>`, and 2.0 is narrowed
D. Ill-formed only because of narrowing

**Answer (A):** Ill-formed: `std::pair` needs two template arguments, and CTAD is all or nothing

**Why:** Class template argument deduction happens only when the template name appears with no argument list at all. Once `<int>` is written, the name refers to `std::pair<int>`, which is an invalid template-id because the second parameter has no default. There is no partial deduction; use `std::pair<int, double>`, `std::pair p{1, 2.0}`, or a factory function.

### Question 4 [tricky] ([over.match.class.deduct], [over.match.list], [vector.overview])

What does this program print?

```cpp
#include <cstdio>
#include <string>
#include <vector>

int main() {
  std::string s = "hello";
  std::vector v{s.begin(), s.end()};
  std::vector w(s.begin(), s.end());
  std::printf("%zu %zu\n", v.size(), w.size());
}
```

A. `5 5`
B. `2 2`
C. `2 5`
D. Nothing: `v` is ill-formed because iterators are not characters

**Answer (C):** `2 5`

**Why:** With braces, initializer-list constructors are tried first, so `std::vector(std::initializer_list<T>)` deduces `T = std::string::iterator`, and `v` holds the two iterators. The single-element copy rule does not apply because there are two elements. With parentheses there is no initializer-list phase, and the iterator-pair guide deduces `std::vector<char>` with five characters.

### Question 5 [tricky] ([temp.deduct.call], [over.match.class.deduct])

Is this program well-formed?

```cpp
template <class T>
struct Holder {
  Holder(T&&) {}
};

int main() {
  int i = 0;
  Holder h(i);
}
```

A. Well-formed: `T&&` is a forwarding reference, so `h` is `Holder<int&>`
B. Ill-formed: `T&&` names a class template parameter, so it is not a forwarding reference and cannot bind `i`
C. Well-formed: `h` is `Holder<int>`, initialized from a copy of `i`
D. Ill-formed: a class template cannot be deduced from a reference parameter

**Answer (B):** Ill-formed: `T&&` names a class template parameter, so it is not a forwarding reference and cannot bind `i`

**Why:** The implicit guide is `template <class T> Holder(T&&) -> Holder<T>`, but [temp.deduct.call] excludes a class template parameter from being a forwarding reference during CTAD. So `T` deduces as `int` from the lvalue, the guide's parameter is `int&&`, and it cannot bind to `i`. Without this rule `Holder<int&>` would be deduced, which is the tempting answer and would usually not be what the class author meant. A user-defined guide with its own `template <class U> Holder(U&&)` parameter does forward.

### Question 6 [tricky] ([over.match.class.deduct], [temp.deduct.guide], [over.match.copy])

What is the type of `b`?

```cpp
#include <string>

template <class T> struct Box { Box(T) {} };
explicit Box(const char*) -> Box<std::string>;

Box a("hi");
Box b = "hi";
```

A. `Box<std::string>`, the same as `a`
B. `Box<const char*>`
C. `Box<const char[3]>`
D. Ill-formed: an explicit guide cannot be used in copy-initialization

**Answer (B):** `Box<const char*>`

**Why:** In copy-initialization that is not list-initialization, explicit candidates are not considered, so the guide is ignored for `b`. That leaves the implicit guide from `Box(T)`, which takes `T` by value and decays the array: `Box<const char*>`. For the direct-initialization of `a`, the guide and the constructor's implicit guide match equally well, and the tie goes to the guide, which is both user-defined and a non-template, so `a` is `Box<std::string>`. Only copy-list-initialization, `Box c = {"hi"};`, would be ill-formed, because there an explicit candidate is considered and then rejected.

### Question 7 [standardese] ([over.match.class.deduct], [dcl.init.aggr])

In C++20, which of these declarations are well-formed?

```cpp
template <class T> struct Agg { T a; T b; };

Agg x{1, 2};     // #1
Agg y(1, 2);     // #2
Agg z{1, 2.0};   // #3
```

A. None: an aggregate needs a user-defined deduction guide
B. Only #1
C. All three, with `z` deduced as `Agg<double>`
D. #1 and #2

**Answer (D):** #1 and #2

**Why:** C++20 adds an aggregate deduction candidate formed from the aggregate's element types and the initializer's elements, used for braced and for parenthesized aggregate initialization, so #1 and #2 deduce `Agg<int>`. In #3 the candidate is `template <class T> Agg(T, T)`, and deducing `T` from `int` and `double` conflicts, so deduction fails and #3 is ill-formed; no common type is computed. "None" is the C++17 answer, when aggregates needed explicit guides.

### Question 8 [standardese] ([dcl.type.class.deduct])

Is this class definition well-formed?

```cpp
#include <vector>

struct S {
  std::vector v{1, 2};
};
```

A. Well-formed: `v` is `std::vector<int>`
B. Well-formed: `v` is `std::vector<std::initializer_list<int>>`
C. Ill-formed: a deduced class type cannot be the type of a non-static data member
D. Ill-formed: a default member initializer cannot use braces with CTAD, but `= {1, 2}` would work

**Answer (C):** Ill-formed: a deduced class type cannot be the type of a non-static data member

**Why:** [dcl.type.class.deduct] allows a placeholder for a deduced class type only in an initializing declaration of a variable, a functional cast, a `new` expression, and the type of a non-type template parameter. A non-static data member is none of these, whatever form its default member initializer takes, so you must write `std::vector<int>`. A `static inline` data member is a variable, so CTAD would work there.

# Type traits and metaprogramming

> A type trait is a class template that maps types to a constant or to another type, answered either by specialization or by the compiler itself. Knowing exactly which question each trait asks, and when its operands are instantiated, separates working metaprograms from subtly wrong ones.

- **Source:** C++ Atlas (https://cppatlas.com/topics/type-traits-and-metaprogramming)
- **Track:** Templates
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [meta.rqmts] (https://eel.is/c++draft/meta.rqmts), [meta.type.synop] (https://eel.is/c++draft/meta.type.synop), [meta.help] (https://eel.is/c++draft/meta.help), [meta.unary.prop] (https://eel.is/c++draft/meta.unary.prop), [meta.rel] (https://eel.is/c++draft/meta.rel), [meta.trans.other] (https://eel.is/c++draft/meta.trans.other), [meta.logical] (https://eel.is/c++draft/meta.logical), [declval] (https://eel.is/c++draft/declval), [stmt.if] (https://eel.is/c++draft/stmt.if), [expr.context] (https://eel.is/c++draft/expr.context), [dcl.pre] (https://eel.is/c++draft/dcl.pre)
- **cppreference links:** [Metaprogramming library](https://en.cppreference.com/w/cpp/meta), [std::integral_constant](https://en.cppreference.com/w/cpp/types/integral_constant), [std::is_trivially_copyable](https://en.cppreference.com/w/cpp/types/is_trivially_copyable), [std::is_constructible](https://en.cppreference.com/w/cpp/types/is_constructible), [std::is_convertible](https://en.cppreference.com/w/cpp/types/is_convertible), [std::decay](https://en.cppreference.com/w/cpp/types/decay), [std::common_type](https://en.cppreference.com/w/cpp/types/common_type), [std::conjunction](https://en.cppreference.com/w/cpp/types/conjunction), [std::declval](https://en.cppreference.com/w/cpp/utility/declval), [if statement (constexpr if)](https://en.cppreference.com/w/cpp/language/if)
- **Prerequisites:** template-instantiation-and-specialization, type-deduction-auto-decltype, sfinae

## The one idea

A type trait is a function evaluated by the compiler. Its argument is a type, and its result is either a constant, such as `std::is_integral<T>::value`, or another type, such as `std::remove_reference<T>::type`. The function is written as a class template, and its "body" is the set of specializations the compiler picks from, or, for the traits that cannot be written in C++, a built-in the compiler answers directly.

Two habits make traits reliable. First, read the precise question a trait asks, because many names promise more or less than they test. Second, know when an operand gets instantiated, because metaprograms fail most often by instantiating something that was never meant to be looked at.

> **Mental model.** A trait is a lookup table indexed by type. Specializations are the rows, `true_type` and `false_type` are the cells, and the compiler fills in the rows nobody could write by hand.

## How a trait is built

The building block is `std::integral_constant<T, v>`, which holds `static constexpr T value = v`, a `type` alias to itself, and conversions to `T` so it can be used directly as a value. `std::true_type` and `std::false_type` are its `bool` instances. A predicate trait derives from one of them, so the answer travels by inheritance and can be dispatched on as a type.

```cpp
#include <type_traits>

template<class T> struct is_ptr : std::false_type {};      // primary: the default row
template<class T> struct is_ptr<T*> : std::true_type {};   // partial specialization
template<class T> struct is_ptr<T* const> : std::true_type {};

template<class T> inline constexpr bool is_ptr_v = is_ptr<T>::value;

static_assert(is_ptr_v<int* const> && !is_ptr_v<int>);
```

C++14 added the `_t` alias templates, so `std::remove_reference_t<T>` replaces `typename std::remove_reference<T>::type`. C++17 added the `_v` variable templates. They are pure conveniences; the class template is still what gets instantiated and what you inherit from when composing traits.

Cv-qualifiers and references interact in a way that trips everyone once. A reference type is never const, because `const` applies to the referred-to type, so `is_const_v<const int&>` is false and `remove_const_t<const int&>` is `const int&` unchanged. Strip the reference first.

```cpp
#include <type_traits>

static_assert(!std::is_const_v<const int&>);
static_assert(std::is_same_v<std::remove_const_t<const int&>, const int&>);
static_assert(std::is_same_v<std::remove_cvref_t<const int&>, int>);
```

## The families and the surprising members

The standard groups traits into primary type categories such as `is_class` and `is_pointer`, composite categories such as `is_arithmetic` and `is_object`, type properties such as `is_trivially_copyable` and `is_constructible`, relationships such as `is_same`, `is_base_of` and `is_convertible`, and transformations such as `decay` and `common_type`. Exactly one primary category is true for any type. The trouble lives in the properties and relationships.

### Trivially copyable is not trivial

`is_trivially_copyable` asks whether the type can be copied with `memcpy`: every eligible copy and move operation is trivial, at least one of them is not deleted, and the destructor is trivial and not deleted. `is_trivial` additionally requires trivial default constructors. A class with a user-provided default constructor is therefore trivially copyable but not trivial. For copying bytes, `is_trivially_copyable` is the trait you want; C++26 deprecates `is_trivial` precisely because it mixes two unrelated questions.

```cpp
#include <type_traits>

struct Init { Init() {} int x; };  // user-provided default constructor
static_assert(std::is_trivially_copyable_v<Init>);  // memcpy is fine
static_assert(!std::is_trivial_v<Init>);
```

### Constructible versus convertible

`is_constructible<T, Args...>` asks whether the variable definition `T t(std::declval<Args>()...);` is well-formed. That is direct-initialization, so explicit constructors count, narrowing is allowed, and, since C++20, parenthesized aggregate initialization counts too. `is_convertible<From, To>` asks whether a function returning `To` could `return std::declval<From>();`, which is copy-initialization, so explicit constructors do not count. Only the immediate context is checked: if the chosen constructor's body would fail to compile, the trait still says true.

```cpp
#include <type_traits>

struct Id { explicit Id(int); };
struct Pair { int a, b; };

static_assert(std::is_constructible_v<Id, int>);       // Id t(0) is fine
static_assert(!std::is_convertible_v<int, Id>);        // Id f() { return 0; } is not
static_assert(std::is_constructible_v<int, double>);   // narrowing allowed with parens
static_assert(std::is_constructible_v<Pair, int, int>); // C++20 Pair(1, 2)
static_assert(std::is_constructible_v<const int&, long>); // binds to a temporary
static_assert(!std::is_constructible_v<int&, long>);
```

### decay, remove_cvref and common_type

`decay_t<T>` applies what passing by value does: it removes the reference, then turns arrays into pointers to their element type, functions into function pointers, and strips top-level cv from everything else. `remove_cvref_t<T>`, added in C++20, only removes the reference and the cv-qualifiers, so arrays stay arrays. Reach for `remove_cvref_t` when you want the "plain" type, and `decay_t` only when you are modelling a by-value copy.

`common_type_t<T, U>` is, roughly, the decayed type of `false ? declval<T>() : declval<U>()`. It follows the usual arithmetic conversions, so `common_type_t<int, unsigned>` is `unsigned` and `common_type_t<char, short>` is `int`, and it always yields a non-reference type.

```cpp
#include <type_traits>

static_assert(std::is_same_v<std::decay_t<const int[3]>, const int*>);
static_assert(std::is_same_v<std::decay_t<int(int)>, int (*)(int)>);
static_assert(std::is_same_v<std::remove_cvref_t<const int (&)[3]>, int[3]>);
static_assert(std::is_same_v<std::common_type_t<const int&, int&>, int>);
static_assert(std::is_same_v<std::common_type_t<int, unsigned>, unsigned>);
```

## Traits the compiler must answer

Some questions cannot be answered by any specialization. Nothing in the language distinguishes a union from a class, detects a trivial copy constructor, tells whether a class is an aggregate or is final, or names an enumeration's underlying type. The standard library implements `is_union`, `is_trivially_copyable`, `is_standard_layout`, `is_aggregate`, `is_final`, `has_virtual_destructor`, `underlying_type` and others with compiler built-ins such as `__is_union(T)`. Many traits also require complete types; asking `is_trivially_copyable` about an incomplete class is undefined behaviour, which is a further reason to treat traits as compiler queries rather than ordinary templates.

Because the library may implement any trait with magic, you are not allowed to add rows to the table.

> **Standardese.** [meta.type.synop] says the behaviour of a program that adds specializations for any of the templates in the type traits subclause is undefined unless otherwise specified. The exceptions are `common_type`, which may be specialized when at least one argument is a program-defined type, and `basic_common_reference` since C++20.

```cpp
#include <type_traits>

struct Fixed {};
// template<> struct std::is_integral<Fixed> : std::true_type {};
// undefined behavior; GCC with libstdc++ accepts it silently,
// while Clang with libc++ rejects it as an invalid specialization
```

Write your own trait, such as `is_my_integral`, instead.

## Unevaluated operands and std::declval

Metaprograms constantly ask "what would this expression be?" without running it. The operands of `sizeof`, `decltype`, `noexcept`, a non-polymorphic `typeid` and `requires` expressions are unevaluated, as described in [expr.context]: they are type-checked but never executed, and functions named inside them are not odr-used.

`std::declval<T>()` is a function declared to return `add_rvalue_reference_t<T>`, so `declval<int>()` is an `int&&` xvalue and `declval<int&>()` is an `int&` lvalue. It conjures a value of any type, even one with no usable constructor. It only works in unevaluated operands: [declval] makes odr-use ill-formed, and both libstdc++ and libc++ enforce that with a `static_assert` in its definition.

```cpp
#include <type_traits>
#include <utility>

struct NoDefault { NoDefault(int); double size() const; };

using R = decltype(std::declval<const NoDefault&>().size());  // double, nothing runs
static_assert(std::is_same_v<R, double>);

// int bad = std::declval<int>();  // ill-formed: odr-use of declval
```

## if constexpr and discarded statements

C++17's `if constexpr` evaluates its condition as a constant expression and discards the branch not taken. Inside a template, a discarded statement is not instantiated, so it can contain code that would be invalid for the current arguments. In any function, `return` statements in a discarded branch do not take part in return type deduction, and an entity odr-used only in a discarded branch needs no definition.

Outside a template nothing is instantiated, so a discarded branch is checked like any other code: it must name declared entities and be otherwise well-formed.

```cpp
#include <type_traits>

template<class T> int to_int(T t) {
  if constexpr (std::is_pointer_v<T>) return *t;  // not instantiated for int
  else if constexpr (std::is_integral_v<T>) return t;
  else static_assert(false, "unsupported type");  // OK since C++23
}
int a = to_int(1);
```

That trailing `static_assert(false)` was ill-formed, no diagnostic required, before P2593. C++23 changed [dcl.pre] so that a `static_assert` inside a template definition is only evaluated on instantiation, and GCC 13 and Clang 17 apply the change in earlier modes too.

> **Pitfall.** `if constexpr` is not the preprocessor. In a non-template function, `if constexpr (false) { undeclared(); }` is ill-formed, and `static_assert(false)` in a discarded branch still fires, because the function is not a template definition.

## conjunction, disjunction and lazy instantiation

`std::conjunction<B...>`, `disjunction` and `negation` arrived in C++17. They are not just spelled-out `&&` and `||`. `conjunction` derives from the first `Bi` whose `value` is false, or from the last one, and it stops: later arguments are never asked for their `::value`, so they are never instantiated. A fold expression such as `(Ts::value && ...)` names every `Ts::value`, and naming a member of a class template specialization instantiates it, before `&&` gets a chance to short-circuit.

```cpp
#include <type_traits>

template<class T> struct Expensive {
  static_assert(sizeof(T) == 0, "must not be instantiated");
  static constexpr bool value = true;
};

static_assert(!std::conjunction_v<std::is_integral<float>, Expensive<int>>);  // OK
// template<class... Ts> constexpr bool all = (Ts::value && ...);
// static_assert(!all<std::is_integral<float>, Expensive<int>>);  // static_assert fires
```

This matters for recursive traits and for traits guarding operations that are hard errors on some types. Note also that a conjunction's result type is one of its arguments, not a fresh `bool_constant`, so it carries that argument's `value_type`.

## What to remember

- A trait is a class template whose specializations, or a compiler built-in, map types to `integral_constant` values or to types; `_t` is C++14 and `_v` is C++17.
- References are never const: `is_const_v<const int&>` is false and `remove_const` leaves it alone.
- `is_trivially_copyable` answers "can I memcpy it"; `is_trivial` also demands trivial default construction and is deprecated in C++26.
- `is_constructible` tests direct-initialization, explicit constructors included; `is_convertible` tests implicit conversion; both check only the immediate context.
- `decay_t` models pass-by-value; `remove_cvref_t` keeps arrays and functions intact; `common_type_t` follows the conditional operator and always decays.
- Specializing a standard trait is undefined behaviour, except `common_type` and `basic_common_reference` for program-defined types.
- `std::declval` is for unevaluated operands only; odr-using it is ill-formed.
- `if constexpr` discards without instantiating only inside templates; in C++23 `static_assert(false)` in such a branch is fine.
- `conjunction` and `disjunction` short-circuit instantiation; a fold over `::value` does not.

## Concept Map Outline

- **Type traits:** Class templates the compiler evaluates to map types to constants or to other types.
  - **How traits are built:** A primary template gives the default answer and specializations add the exceptions.
    - **integral_constant:** Holds a static constexpr value; true_type and false_type are its bool instances.
    - **_t and _v helpers:** Alias templates arrived in C++14 and variable templates in C++17; both are conveniences.
    - **References are never const:** is_const_v<const int&> is false, and remove_const leaves a reference unchanged.
  - **Surprising properties:** Several trait names promise more or less than the question they actually ask.
    - **Trivially copyable:** Asks whether memcpy is valid; a user-provided default constructor does not matter.
    - **is_trivial:** Also requires trivial default construction; deprecated in C++26.
    - **is_constructible:** Tests direct-initialization T t(args...), so explicit constructors and narrowing count.
    - **is_convertible:** Tests copy-initialization through a return statement, so explicit constructors do not count.
  - **Transformations:** Traits whose result is a type, read through the _t alias.
    - **decay:** Models pass-by-value: drops references and cv, turns arrays and functions into pointers.
    - **remove_cvref:** C++20; strips only references and cv, so arrays stay arrays.
    - **common_type:** Decayed type of the conditional operator; int and unsigned give unsigned.
  - **Compiler-backed traits:** Questions no specialization can answer are implemented with built-ins.
    - **Built-in intrinsics:** is_union, is_aggregate, is_final and underlying_type need compiler support.
    - **Specializing is UB:** Adding specializations of standard traits is undefined behavior unless explicitly permitted.
    - **Permitted exceptions:** common_type and, since C++20, basic_common_reference may be specialized for program-defined types.
  - **Unevaluated contexts:** Operands that are type-checked but never executed or odr-used.
    - **The operators:** sizeof, decltype, noexcept, non-polymorphic typeid and requires expressions.
    - **std::declval:** Returns add_rvalue_reference_t<T>; odr-using it is ill-formed.
  - **Control at compile time:** Choosing code paths and combining predicates without unwanted instantiation.
    - **if constexpr:** C++17; a discarded branch is not instantiated, but only inside a template.
    - **static_assert(false):** Fine in a discarded template branch since C++23 (P2593); still fires in non-templates.
    - **conjunction:** Stops at the first false argument and never instantiates the rest; a fold over ::value does.

## Standardese Quiz Questions

### Question 1 [warmup] ([meta.unary.prop], [dcl.ref])

Which of these `static_assert`s fails?

```cpp
#include <type_traits>

static_assert(std::is_const_v<const int>);                                   // #1
static_assert(std::is_const_v<const int&>);                                  // #2
static_assert(std::is_same_v<std::remove_cvref_t<const int&>, int>);         // #3
static_assert(std::is_same_v<std::remove_reference_t<const int&>, const int>); // #4
```

A. #1
B. #3
C. #2
D. #4
E. None of them

**Answer (C):** #2

**Why:** A reference type is never cv-qualified: the `const` in `const int&` belongs to the referred-to type, so `is_const_v<const int&>` is false, so #2 fails and makes the program ill-formed. The same reasoning means `remove_const_t<const int&>` is unchanged. #3 and #4 hold because they remove the reference first, which is why `remove_cvref_t` exists.

### Question 2 [warmup] ([meta.unary.prop], [meta.rel], [dcl.init.general])

What are the values of `A` and `B`?

```cpp
#include <type_traits>

struct Id { explicit Id(int); };

constexpr bool A = std::is_constructible_v<Id, int>;
constexpr bool B = std::is_convertible_v<int, Id>;
```

A. `A` is true, `B` is true
B. `A` is false, `B` is false
C. `A` is false, `B` is true
D. `A` is true, `B` is false

**Answer (D):** `A` is true, `B` is false

**Why:** `is_constructible<Id, int>` asks whether `Id t(std::declval<int>());` is well-formed, which is direct-initialization, so the explicit constructor is usable and `A` is true. `is_convertible<int, Id>` asks whether a function returning `Id` can `return` an `int`, which is copy-initialization and ignores explicit constructors, so `B` is false. Treating the two traits as synonyms is the usual mistake.

### Question 3 [warmup] ([meta.trans.other], [conv.array])

What type is `D`?

```cpp
#include <type_traits>

using D = std::decay_t<const int (&)[3]>;
```

A. `int*`
B. `const int*`
C. `int[3]`
D. `const int[3]`

**Answer (B):** `const int*`

**Why:** `decay` first removes the reference, leaving `const int[3]`, and then applies array-to-pointer conversion, giving a pointer to the element type `const int`. The `const` is not top-level on a pointer to const, so it survives. `int[3]` is what `remove_cvref_t` would give, since it keeps arrays as arrays.

### Question 4 [tricky] ([class.prop], [meta.unary.prop])

What are the values of `C` and `T`?

```cpp
#include <type_traits>

struct Init {
  Init() {}
  int x;
};

constexpr bool C = std::is_trivially_copyable_v<Init>;
constexpr bool T = std::is_trivial_v<Init>;
```

A. `C` is true, `T` is false
B. Both are true
C. Both are false
D. `C` is false, `T` is true

**Answer (A):** `C` is true, `T` is false

**Why:** Trivially copyable only looks at copy and move operations and the destructor, all of which are implicitly declared and trivial here, so `C` is true and `memcpy` is a valid way to copy an `Init`. A trivial class must also have a trivial default constructor, and `Init()` is user-provided, so `T` is false. A user-written constructor does not stop byte-wise copying.

### Question 5 [tricky] ([meta.logical], [temp.inst])

Which declaration makes the program ill-formed?

```cpp
#include <type_traits>

template<class T> struct Expensive {
  static_assert(sizeof(T) == 0, "must not be instantiated");
  static constexpr bool value = true;
};

template<class... Ts> constexpr bool all = (Ts::value && ...);

constexpr bool p = std::conjunction_v<std::is_integral<float>, Expensive<int>>; // #1
constexpr bool q = all<std::is_integral<float>, Expensive<int>>;              // #2
```

A. Neither: both short-circuit after `is_integral<float>`
B. Only #1
C. Both
D. Only #2

**Answer (D):** Only #2

**Why:** `conjunction` inherits from the first argument whose `value` is false and never asks later arguments for `::value`, so `Expensive<int>` is not instantiated in #1. The fold in #2 names `Expensive<int>::value`, and naming a member of a class template specialization instantiates the class, firing its `static_assert`, so #2 is ill-formed; the `&&` never gets a chance to short-circuit. Short-circuiting the evaluation is not the same as short-circuiting instantiation.

### Question 6 [tricky] ([stmt.if], [dcl.pre])

In C++23, which of these functions is well-formed?

```cpp
#include <type_traits>

void f() {
  if constexpr (sizeof(int) == 0) { static_assert(false); }
}

template<class T> void g() {
  if constexpr (sizeof(T) == 0) { static_assert(false); }
}
```

A. Both
B. Only `f`
C. Only `g`
D. Neither, because `static_assert(false)` is always ill-formed

**Answer (C):** Only `g`

**Why:** Discarding a branch of `if constexpr` only prevents instantiation, and only templates are instantiated. C++23 (P2593) changed `static_assert` so that inside a template definition it is evaluated on instantiation, which makes `g` fine. `f` is not a template, so its discarded branch is checked like ordinary code and the failing `static_assert` makes `f` ill-formed. The last option describes the rule before P2593, which compilers now apply retroactively.

### Question 7 [standardese] ([meta.type.synop], [namespace.std])

What does the C++23 standard say about this program?

```cpp
#include <type_traits>

struct Fixed {};

template<>
struct std::is_integral<Fixed> : std::true_type {};

int main() { return std::is_integral_v<Fixed>; }
```

A. It is well-formed and returns 1
B. Ill-formed: `is_integral` is declared `final`
C. Implementation-defined
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** [meta.type.synop] makes adding a specialization for any type trait template undefined behavior unless the trait's specification allows it, and only `common_type` and `basic_common_reference` do. Specializing a standard template for a program-defined type is allowed in general by [namespace.std], which makes the first option tempting, but the traits subclause overrides that. In practice GCC with libstdc++ accepts this, while Clang with libc++ rejects it.

### Question 8 [standardese] ([declval], [expr.context], [basic.def.odr])

Which use of `std::declval` is ill-formed?

```cpp
#include <utility>

struct NoDefault { NoDefault(int); int get() const; };

using A = decltype(std::declval<NoDefault>().get());       // #1
constexpr auto B = sizeof(std::declval<NoDefault>());      // #2
constexpr bool C = noexcept(std::declval<NoDefault>().get()); // #3
int D = std::declval<NoDefault>().get();                 // #4
```

A. #1, because `NoDefault` has no default constructor
B. #4 only
C. #2 and #4
D. None of them; `declval` merely returns an rvalue reference

**Answer (B):** #4 only

**Why:** The operands of `decltype`, `sizeof` and `noexcept` are unevaluated, so `declval` is not odr-used there and any type, constructible or not, is fine. #4 is an evaluated expression, which odr-uses `declval`, and [declval] makes that ill-formed; both libstdc++ and libc++ diagnose it with a `static_assert`. `sizeof` is a common doubt, but it is as unevaluated as `decltype`.

# CRTP and Deducing This

> Achieve zero-overhead static polymorphism with the Curiously Recurring Template Pattern, then eliminate its boilerplate and fourfold member overloads using C++23 explicit object parameters.

- **Source:** C++ Atlas (https://cppatlas.com/topics/crtp-and-deducing-this)
- **Track:** Templates
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [class.derived] (https://eel.is/c++draft/class.derived), [dcl.fct] (https://eel.is/c++draft/dcl.fct), [class.mfct] (https://eel.is/c++draft/class.mfct), [temp.dep] (https://eel.is/c++draft/temp.dep), [over.match.funcs] (https://eel.is/c++draft/over.match.funcs), [class.mem] (https://eel.is/c++draft/class.mem)
- **cppreference links:** [Curiously Recurring Template Pattern](https://en.cppreference.com/w/cpp/language/crtp), [Non-static member functions](https://en.cppreference.com/w/cpp/language/member_functions), [The this pointer](https://en.cppreference.com/w/cpp/language/this), [Dependent names](https://en.cppreference.com/w/cpp/language/dependent_name), [std::forward_like](https://en.cppreference.com/w/cpp/utility/forward_like), [Empty base optimization](https://en.cppreference.com/w/cpp/language/ebo)
- **Prerequisites:** inheritance-and-virtual-functions, value-categories, forwarding-references-and-perfect-forwarding

When concrete types are known at compile time, virtual dispatch forces unnecessary indirection through a `vptr` and blocks inlining across interfaces. C++ solves static polymorphism via two complementary techniques: the classic **Curiously Recurring Template Pattern** (CRTP) and C++23's **explicit object parameters** (commonly called *deducing `this`*).

## Static polymorphism with CRTP

In CRTP, a derived class `Widget` inherits from a class template `Base<Widget>`, passing its own type as the template argument (`[class.derived]`):

```cpp
template <class Derived>
class CounterMixin {
    friend Derived;
    CounterMixin() = default; // prevents accidental Base<WrongType> inheritance
public:
    void bump() {
        static_cast<Derived&>(*this).on_bump();
    }
    const Derived& self() const {
        return static_cast<const Derived&>(*this);
    }
};

struct Metric : CounterMixin<Metric> {
    int count = 0;
    void on_bump() { ++count; }
};
```

Because `CounterMixin<Metric>` knows the exact type `Metric` at compile time, `static_cast<Derived&>(*this)` resolves to `Metric::on_bump()` statically—with zero `vptr` storage overhead, zero vtable lookup, and full inlining. Standard and production libraries rely on CRTP extensively for mixins (like `std::ranges::view_interface` or `std::enable_shared_from_this`), static interfaces, and empty base optimization (`[class.mem]`).

## Classic CRTP pitfalls: lookup, timing, and friends

Three recurring traps catch authors writing classic CRTP bases:

1. **Wrong template argument copy-paste:** Writing `struct B : CounterMixin<A>` instead of `CounterMixin<B>` causes undefined behavior when `CounterMixin<A>` casts `*this` to `A&`! Guard against this by making `CounterMixin`'s constructor `private` and declaring `friend Derived;`.
2. **Incomplete `Derived` during instantiation:** Inside the class body of `CounterMixin<Metric>`, `Metric` is still an incomplete type while `CounterMixin<Metric>` is being instantiated as `Metric`'s base. Member *function bodies* may reference `Derived` (since function bodies are instantiated lazily upon use), whereas non-static data members or signature return types like `typename Derived::value_type` will fail because `Derived` is not complete yet.
3. **Dependent base name lookup (`[temp.dep]`):** When a class template `Child<T>` inherits from a dependent base `Base<T>`, two-phase lookup does **not** examine `Base<T>` during unqualified lookup. Access base members via `this->member` or `Base<T>::member`.

> **Pitfall.** Never call `static_cast<Derived&>(*this)` inside `Base<Derived>`'s constructor or destructor. When `Base`'s constructor executes, `Derived`'s subobject has not begun its lifetime yet; when `Base`'s destructor runs, `Derived` has already been destroyed. Either access invokes undefined behavior (`[class.cdtor]`).

## C++23 explicit object parameters (Deducing This)

C++23 (`P0847R7`) introduces **explicit object member functions** (`[dcl.fct]`, `[class.mfct]`): instead of an implicit hidden `this` pointer, the first parameter carries the keyword `this` and gives the receiver an explicit name and deducible template type.

Before C++23, wrapper types such as `std::optional` or fluent builders had to write four nearly identical accessor overloads (`&`, `const&`, `&&`, and `const&&`) just to forward a stored member with matching constness and value category. Worse, adding `&` and `&&` ref-qualifiers to a classic CRTP base required duplicating every mixin method too.

> **Mental model.** An explicit object parameter makes the receiver parameter behave like any ordinary function parameter whose type and value category (`&`, `const&`, `&&`, `const&&`, or even derived subclass type `Self`) are deduced straight from the call expression.

Look at how one function template replaces all four accessor overloads—while also deducing cv-qualification and preserving value category on member fields with `std::forward_like`:

```cpp
#include <string>
#include <utility>

struct Cell {
    std::string data;

    template <class Self>
    auto&& value(this Self&& self) {
        return std::forward_like<Self>(self.data);
    }
};
```

Wait—why use `std::forward_like<Self>(self.data)` instead of `std::forward<Self>(self).data`? If `data` were a reference member (`std::string& data;`), `[expr.ref]` dictates that `std::forward<Cell>(self).data` evaluates to an **lvalue** `std::string&` even on an rvalue `Cell&&`, silently blocking moves! `std::forward_like<Self>(self.data)` merges `Self`'s constness and value category directly onto `self.data`, returning `std::string&&` when `self` is a non-const rvalue.

> **Standardese.** Under `[dcl.fct]` and `[class.mfct]`, a member function with an explicit object parameter has **no implicit `this` pointer** inside its body, cannot be `static`, `virtual`, `const`, `volatile`, or ref-qualified (`&`/`&&`), and taking its address yields a **plain function pointer** (`auto fn = &Cell::value<Cell&>;` has type `std::string& (*)(Cell&)`), not a pointer-to-member-function.

## CRTP without templates, recursive lambdas, and pass-by-value this

Because `Self` in `(this Self&& self)` deduces to the actual expression type at the call site—including any **derived class**—CRTP no longer requires making the base class a template at all:

```cpp
struct Printable {
    void print_twice(this auto&& self) {
        self.emit();
        self.emit();
    }
};

struct Badge : Printable {
    int hits = 0;
    void emit() { ++hits; }
};

auto factorial = [](this auto&& self, int n) -> int {
    return n <= 1 ? 1 : n * self(n - 1);
};
```

Look at the cleanup achieved in `Printable` and `factorial`:

- **Non-template CRTP:** `Printable` is an ordinary non-template class; `Badge` simply inherits `Printable`, eliminating `Base<WrongType>` bugs, dependent base lookup issues, and `static_cast<Derived&>(*this)` boilerplate.
- **Recursive lambdas:** Writing `(this auto&& self, int n)` inside a lambda binds `self` directly to the closure object, giving zero-overhead self-recursion without `std::function` type erasure or passing the lambda to itself.
- **Pass-by-value `this`:** Small scalar-like types can declare `void tick(this Counter copy)` to receive `this` in a register by value rather than indirectly by pointer.

Compare the three dispatch mechanisms side by side to choose the right tool:

| Mechanism | Runtime cost | Base template needed? | Eliminates 4x `&`/`&&` overloads? | Heterogeneous container support? |
| --- | --- | --- | --- | --- |
| Virtual dispatch | `vptr` + indirect call | No | No | Yes (`Base*`) |
| Classic CRTP | Zero (static inline) | Yes (`Base<Derived>`) | No | No |
| Deducing `this` (C++23) | Zero (static inline) | No | Yes (`this Self&&`) | No |

Note two remaining boundaries when adopting deducing `this`:

- Inside `Printable::print_twice(this auto&& self)`, calling `self.emit()` respects normal member access rules—so `Badge::emit()` must be `public` (or `Printable` declared a `friend`), whereas private helpers on `Printable` itself require care because `self` carries static type `Badge`, not `Printable`.
- Because overload resolution treats an explicit object parameter like a normal first parameter (`[over.match.funcs]`), a derived class can cleanly shadow or customize behavior without template specialization, while pass-by-value `this` removes aliasing concerns on immutable small handles.

## What to remember

- Classic CRTP achieves zero-overhead static polymorphism via `Base<Derived>` and `static_cast<Derived&>(*this)`, but breaks if `Base` invokes `Derived` during construction/destruction or relies on incomplete members of `Derived`.
- Always guard classic CRTP constructors (`private` + `friend Derived`) to prevent inheriting `Base<WrongType>`, and qualify dependent base members with `this->`.
- C++23 explicit object parameters (`this Self&& self`) eliminate quadrupled `&`/`const&`/`&&`/`const&&` overloads, simplify CRTP into non-template bases, and enable direct recursive lambdas.
- Explicit object functions have no implicit `this`, forbid `virtual`/`static`/`const`/ref-qualifiers, and produce regular function pointers when their address is taken.
- Use `std::forward_like<Self>(self.member)` when returning a member from `this Self&& self` so reference members still respect the owner's constness and rvalue-ness.

## Concept Map Outline

- **CRTP & Deducing This:** Compile-time polymorphism evolved from template base casts to C++23 explicit object parameters.
  - **Classic CRTP:** A derived class passes itself as a template argument to its own base class.
    - **Static Dispatch Cast:** Base invokes derived methods via static_cast<Derived&>(*this) with full inlining.
    - **Zero Vtable Cost:** CRTP avoids vptr memory overhead and indirect runtime calls entirely.
    - **Mixin Injection:** Reusable interfaces like view_interface inject operators onto concrete derived types.
    - **Friend Guard Pattern:** Making Base's constructor private and friending Derived prevents inheriting Base<WrongType>.
  - **CRTP Constraints:** Instantiation order and two-phase lookup create subtle classic CRTP hazards.
    - **Incomplete Derived Type:** Derived is incomplete while Base<Derived> instantiates, restricting uses to member bodies.
    - **Ctor and Dtor UB:** Casting *this to Derived inside Base's constructor or destructor triggers undefined behavior.
    - **Dependent Base Lookup:** Derived templates inheriting dependent bases must access base members via this-> or Base<T>::.
  - **Explicit Object Param:** C++23 lets the receiver parameter be written explicitly with this Self&&.
    - **this Self&& Syntax:** Annotating the first parameter with this deduces both object type and value category.
    - **No Implicit this:** Explicit object member functions forbid using the implicit this pointer inside their body.
    - **Disallowed Qualifiers:** Explicit object parameters cannot be combined with virtual, static, const, or ref-qualifiers.
    - **Plain Function Pointer:** Taking the address of an explicit object function yields a regular function pointer, not a member pointer.
  - **Overload Unification:** A single deducing-this template replaces four cv- and ref-qualified member overloads.
    - **Single Template Body:** One template handles &, const&, &&, and const&& receivers without code duplication.
    - **Deduces Derived Self:** Calling a base explicit-object method on Derived deduces Self directly as Derived.
    - **std::forward_like Member:** Merges Self's constness and value category onto a returned field or reference member.
  - **Modern Idioms:** Deducing this simplifies static mixins, recursive closures, and small value types.
    - **Non-Template CRTP:** Mixins become ordinary non-template bases dispatching to self.impl() cleanly.
    - **Recursive Lambdas:** Naming this auto&& self inside a lambda enables zero-overhead self-recursion.
    - **Pass-By-Value this:** Taking this T copy passes small types directly in registers rather than by pointer.

## Standardese Quiz Questions

### Question 1 [warmup] ([class.derived], [temp.inst])

What primary performance advantage does CRTP offer over virtual dispatch when all concrete types are known at compile time?

A. CRTP lets you store unrelated derived types inside a single std::vector<Base>
B. Calls resolve statically via static_cast with no vptr memory overhead, no vtable lookup, and full inlining
C. CRTP moves object construction onto the stack automatically
D. CRTP allows overriding private virtual functions without virtual destructors

**Answer (B):** Calls resolve statically via static_cast with no vptr memory overhead, no vtable lookup, and full inlining

**Why:** Because Base<Derived> knows the concrete Derived type at compile time, static_cast<Derived&>(*this) resolves calls statically, eliminating the hidden vptr per object and enabling inline optimization.

### Question 2 [warmup] ([dcl.fct], [expr.prim.lambda])

What problem does C++23's explicit object parameter `(this auto&& self)` solve directly inside a lambda expression?

```cpp
auto fib = [](this auto&& self, int n) -> int {
    return n <= 1 ? n : self(n - 1) + self(n - 2);
};
```

A. It makes the lambda capture local variables by move automatically
B. It turns the lambda into a virtual function callable through a base pointer
C. It evaluates every call to the lambda as consteval
D. It lets the lambda call itself recursively without std::function or passing itself as an extra argument

**Answer (D):** It lets the lambda call itself recursively without std::function or passing itself as an extra argument

**Why:** Under [dcl.fct] and [expr.prim.lambda], naming an explicit object parameter `this auto&& self` binds `self` to the lambda's closure object, enabling direct, zero-overhead recursion.

### Question 3 [tricky] ([expr.prim.this], [class.mfct])

Why does the member function `Widget::read` below fail to compile in C++23?

```cpp
struct Widget {
    int count = 5;
    int read(this const Widget& self) {
        return this->count;
    }
};
```

A. Inside an explicit object member function there is no implicit `this` pointer; it must write `self.count`
B. An explicit object parameter cannot be const-qualified as `const Widget&`
C. Explicit object member functions must be templates
D. Members cannot be accessed inside explicit object functions unless declared mutable

**Answer (A):** Inside an explicit object member function there is no implicit `this` pointer; it must write `self.count`

**Why:** Under [expr.prim.this] and [class.mfct], `this` is not in scope as an expression inside an explicit object member function body. All member access must go explicitly through the named parameter `self` (`self.count`).

### Question 4 [tricky] ([dcl.fct], [expr.unary.op])

What is the exact type of `fn` when taking the address of explicit object member function `Counter::bump`?

```cpp
struct Counter {
    int value = 0;
    void bump(this Counter& self) { ++self.value; }
};
auto fn = &Counter::bump;
```

A. void (Counter::*)()
B. void (Counter::*)(Counter&)
C. void (*)(Counter&)
D. Ill-formed: you cannot take the address of an explicit object member function

**Answer (C):** void (*)(Counter&)

**Why:** Under [dcl.fct] and [expr.unary.op], an explicit object member function behaves like a non-member function for pointer formation: `&Counter::bump` yields a plain function pointer `void (*)(Counter&)`, not a pointer-to-member-function.

### Question 5 [standardese] ([dcl.fct], [class.mfct])

Which declaration of an explicit object member function is legal in C++23?

A. virtual void draw(this Shape& self);
B. void draw(this const Shape& self) noexcept;
C. void draw(this Shape& self) const;
D. static void draw(this Shape& self);

**Answer (B):** void draw(this const Shape& self) noexcept;

**Why:** Under [dcl.fct], a function declaration with an explicit object parameter cannot be `virtual`, `static`, cv-qualified (`const`/`volatile`), or ref-qualified (`&`/`&&`)—those properties belong on the explicit object parameter itself. Exception specifications like `noexcept` remain valid.

### Question 6 [standardese] ([expr.ref], [forward])

In `Box` below, why does `std::move(b).bad()` yield `std::string&` instead of `std::string&&`, whereas `std::move(b).good()` yields `std::string&&`?

```cpp
struct Box {
    std::string& item;
    template <class Self>
    decltype(auto) bad(this Self&& self) {
        return std::forward<Self>(self).item;
    }
    template <class Self>
    decltype(auto) good(this Self&& self) {
        return std::forward_like<Self>(self.item);
    }
};
```

A. std::forward<Self>(self) ignores template deduction when Self is an explicit object parameter
B. Member access on a template always decays rvalues to lvalues
C. std::forward_like forces a copy of item onto the stack
D. Under [expr.ref], accessing a reference member `E1.m` where `m` is `T&` produces an lvalue even when `E1` is an rvalue, whereas `std::forward_like<Self>` applies Self's value category onto `item`

**Answer (D):** Under [expr.ref], accessing a reference member `E1.m` where `m` is `T&` produces an lvalue even when `E1` is an rvalue, whereas `std::forward_like<Self>` applies Self's value category onto `item`

**Why:** By [expr.ref], member access on an rvalue yields an xvalue only for non-reference, non-static data members; when the member itself is an lvalue reference (`std::string&`), `E1.item` stays an lvalue. `std::forward_like<Self>(self.item)` transfers `Self`'s constness and value category onto `item` ([forward]).

# Non-type template parameters

> A non-type template parameter makes a compile-time value part of a type's identity. Which types may carry such values, which arguments are acceptable, and when two arguments name the same specialization all follow from one requirement, that the compiler must be able to decide template-argument equivalence.

- **Source:** C++ Atlas (https://cppatlas.com/topics/non-type-template-parameters)
- **Track:** Templates
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [temp.param] (https://eel.is/c++draft/temp.param), [temp.arg.nontype] (https://eel.is/c++draft/temp.arg.nontype), [temp.type] (https://eel.is/c++draft/temp.type), [expr.const] (https://eel.is/c++draft/expr.const), [dcl.type.auto.deduct] (https://eel.is/c++draft/dcl.type.auto.deduct), [expr.prim.lambda.closure] (https://eel.is/c++draft/expr.prim.lambda.closure)
- **cppreference links:** [Template parameters and template arguments](https://en.cppreference.com/w/cpp/language/template_parameters), [Constant expressions](https://en.cppreference.com/w/cpp/language/constant_expression), [Lambda expressions](https://en.cppreference.com/w/cpp/language/lambda)
- **Prerequisites:** template-instantiation-and-specialization, constant-expressions, template-argument-deduction, class-template-argument-deduction

## The one idea

A non-type template parameter, or NTTP, puts a value into a type. `std::array<int, 3>` and `std::array<int, 4>` are different types because `3` and `4` are different values, and the program needs to agree, in every translation unit, on whether two template argument lists name the same specialization. That question is called template-argument equivalence.

Almost every rule about NTTPs exists to keep that question answerable at compile time, without running user code: which types are allowed, which arguments are acceptable, and why the parameter of class type behaves like an object while the parameter of `int` type does not.

> **Mental model.** An NTTP value is part of the mangled name. If the compiler could not write the value down and compare it member by member, the type is not allowed.

## Which types are allowed, by version

| Standard | Adds |
| --- | --- |
| C++98 | integral and enumeration types, pointers to objects and functions, lvalue references to objects and functions, pointers to members |
| C++11 | `std::nullptr_t` |
| C++17 | placeholder types: `auto` and `decltype(auto)` |
| C++20 | floating-point types and structural literal class types, plus arrays of these inside classes |

The parameter's declared type is adjusted like a function parameter's. An array type becomes a pointer, a function type becomes a pointer to function, and top-level cv-qualifiers are dropped, so `template<const int N>` declares a parameter of type `int`.

C++20 defines a **structural type** as a scalar type, an lvalue reference type, or a literal class type whose bases and non-static data members are all public and non-mutable, and whose base and member types are themselves structural or arrays of structural types. User-provided constructors are allowed, as long as the class is literal. The standard does not promise that library types are structural. In practice GCC and Clang accept `std::array` and `std::pair` of structural types, and reject `std::string` and `std::string_view`, whose members are private.

```cpp
#include <string>

struct Point { int x, y; };                 // structural
class Hidden { int v = 0; public: constexpr Hidden() = default; };
struct Cache { mutable int hits; };

template<Point P> struct A {};              // OK since C++20
template<double D> struct B {};             // OK since C++20
// template<Hidden H> struct C {};          // error: private member
// template<Cache K> struct E {};           // error: mutable member
// template<std::string S> struct F {};     // error: not structural
```

> **Standardese.** [temp.param] lists the permitted types: a structural type, a type containing a placeholder, or a placeholder for a deduced class type. The definition of structural type in the same section is what C++20 compilers check, and GCC and Clang both report "not a structural type" when it fails.

## Arguments are converted constant expressions

An argument for an NTTP of non-reference type must be a converted constant expression of the parameter's type, as defined in [expr.const]. Only a short list of conversions is allowed: integral promotions and integral conversions that are not narrowing, floating-point promotions and exact floating-point conversions, array-to-pointer and function-to-pointer conversions, qualification conversions, null pointer conversions from `std::nullptr_t`, and user-defined conversions built from these.

Two consequences surprise people. Narrowing is an error, even when the value would fit after wrapping. And an integer argument for a `double` parameter is rejected, because the integral-to-floating conversion is not on the list.

```cpp
template<unsigned char C> struct Byte {};
template<double D> struct Scale {};

Byte<200> ok;
// Byte<300> bad;     // error: narrowing conversion of 300
Scale<1.0> fine;
// Scale<1> no;       // error: int to double is not allowed here
```

For a class-type parameter, the argument copy-initializes the parameter, so a constexpr converting constructor works: given `struct Q { int v; constexpr Q(int x) : v(x) {} };`, writing `X<5>` for `template<Q P> struct X` is fine.

## Pointer and reference arguments

Before C++17, an argument for a pointer or reference parameter had to be spelled as the address of, or the name of, an object or function with linkage. C++17 relaxed that to any constant expression, then listed what the pointer or reference may not designate: a temporary, a string literal, the result of `typeid`, the predefined `__func__` variable, and, in C++17 only, any subobject. C++20 allows subobjects, so `&arr[1]` and `&obj.member` became valid arguments, while subobjects of the forbidden objects remain forbidden.

```cpp
template<const char* P> struct Tag {};
template<int* P> struct Slot {};
int arr[3];

// Tag<"hi"> t1;           // error: string literal
constexpr char name[] = "hi";
Tag<name> t2;              // OK: names an object with static storage
Slot<&arr[1]> s;           // OK since C++20; an error in C++17

void f() {
  static constexpr char local[] = "hi";
  Tag<local> t3;           // OK since C++17; C++14 required linkage
  (void)t3;
}
```

> **Pitfall.** A string literal is rejected because two identical literals need not be the same object, so `Tag<"hi">` in two places could not be guaranteed to name one type. The usual way to pass text is a class-type NTTP that holds the characters by value, shown below.

A reference parameter cannot bind to a temporary either, so `template<const int& R>` does not accept `X<42>`.

## auto parameters

C++17 lets a parameter be declared with a placeholder. `template<auto V>` deduces the parameter's type from the argument, as if by `auto x = argument;`, and `template<decltype(auto) V>` deduces it as `decltype` would, which can make it a reference. A pack `template<auto... Vs>` may hold values of different types.

The deduced type is part of the identity. `X<1>` and `X<1u>` are different specializations because their parameters have different types, even though the values compare equal.

```cpp
#include <type_traits>

template<auto V> struct X {};
template<auto... Vs> struct List {};

static_assert(!std::is_same_v<X<1>, X<1u>>);   // int versus unsigned
static_assert(std::is_same_v<X<1>, X<2 - 1>>); // same type, same value
List<1, 'c', true> mixed;                       // int, char, bool
```

Since C++20 a placeholder also accepts class values. `template<auto V>` given `Point{1, 2}` deduces `Point`, provided the deduced type is structural; if it is not, the program is ill-formed.

## Template-argument equivalence

[temp.type] decides when two specializations are the same. Two values of an NTTP are template-argument-equivalent when they have the same type and integral values compare equal, floating-point values are identical, pointers have the same pointer value, pointers to members refer to the same member or are both null, references refer to the same entity, and class values have equivalent subobjects and reference members, recursively.

"Identical" is deliberate for floating point: it is not `==`. Positive and negative zero compare equal but are different values, so they produce different types.

```cpp
#include <type_traits>

template<double D> struct F {};

static_assert(!std::is_same_v<F<0.0>, F<-0.0>>);  // distinct specializations
static_assert(std::is_same_v<F<0.5>, F<1.0 / 2>>); // same value, same type
```

Pointers compare by address, not by what they point to. Two distinct arrays holding the same characters give two different specializations, because the identity of the object is the value. Class-type parameters work the other way round and compare their contents, which is exactly why a wrapper that stores characters by value can do what a `const char*` parameter cannot.

## Class-type parameters and template parameter objects

Inside the template, an NTTP of scalar type is a prvalue, so you cannot take its address. An NTTP of class type is different: its name denotes a **template parameter object**, an object of type `const T` with static storage duration. There is exactly one such object for each distinct value across the whole program, so every specialization with an equivalent argument shares it, and a reference to it never dangles.

```cpp
#include <cstdio>

struct P { int x; };
template<P V> const P& get() { return V; }   // fine: V lives for the whole program
// template<int N> const int* addr() { return &N; }  // error: N is a prvalue

int main() {
  std::printf("%d %d\n", &get<P{1}>() == &get<P{1}>(),  // 1: one object
                         &get<P{1}>() == &get<P{2}>()); // 0
}
```

This is what makes string-literal wrappers work. A small class holds a character array, and a constructor taking a reference to an array lets class template argument deduction work out its size. The parameter is declared with the class template name alone, a placeholder for a deduced class type, which C++20 allows.

```cpp
#include <cstddef>
#include <cstdio>

template<std::size_t N> struct fixed_string {
  char data[N];
  constexpr fixed_string(const char (&s)[N]) {
    for (std::size_t i = 0; i < N; ++i) data[i] = s[i];
  }
};

template<fixed_string S> struct Name {
  static constexpr const char* get() { return S.data; }
};

int main() { std::puts(Name<"hello">::get()); }  // prints hello
```

Two `Name<"hello">` written in different files are the same type, because the arguments are compared character by character rather than by address.

### Lambdas as arguments

C++20 also allows lambda expressions to appear in template arguments. A capture-less lambda's closure type has no data members, and CWG 2845 clarified that such a closure type is structural, so it can be the argument of an `auto` parameter and called inside the template. Every lambda expression has a unique closure type, so two textually identical lambdas give two different specializations.

```cpp
template<auto F> int call() { return F(); }

int seven = call<[] { return 7; }>();  // OK since C++20
```

## What to remember

- An NTTP value is part of the type, so its type must allow comparison at compile time: that is the structural-type rule.
- C++11 added `nullptr_t`, C++17 added `auto` and `decltype(auto)`, and C++20 added floating-point and structural class types.
- Structural classes have only public, non-mutable members and bases of structural type; `std::string` and `std::string_view` are rejected in practice.
- Arguments are converted constant expressions: narrowing is ill-formed, and `int` to `double` is not allowed.
- Pointer and reference arguments cannot designate string literals, temporaries, `typeid` results or `__func__`; subobjects are allowed only since C++20.
- `X<1>` and `X<1u>` differ for an `auto` parameter, and `0.0` and `-0.0` differ for a `double` parameter.
- A class-type NTTP names a single `const` template parameter object with static storage duration, shared by all equivalent arguments.
- Scalar NTTPs are prvalues; you cannot take their address.
- Text goes in as a `fixed_string`-style class, not as `const char*`.

## Concept Map Outline

- **Non-type template parameters:** Compile-time values that become part of a specialization's identity.
  - **Allowed types:** The set grew from integers and addresses to floating point and classes.
    - **C++98 and C++11:** Integral, enumeration, object and function pointers, lvalue references, member pointers, nullptr_t.
    - **C++20 additions:** Floating-point types and structural literal class types.
    - **Structural class:** Literal, with all bases and non-static members public, non-mutable and structural.
    - **Type adjustments:** Arrays and functions decay to pointers and top-level cv is dropped.
  - **Acceptable arguments:** Each argument must be a converted constant expression of the parameter type.
    - **No narrowing:** Byte<300> for an unsigned char parameter is ill-formed.
    - **No int to double:** Floating-integral conversions are not allowed, so Scale<1> fails for a double parameter.
    - **Class arguments:** A class parameter is copy-initialized, so constexpr converting constructors work.
  - **Pointers and references:** What an address argument may designate changed in C++17 and C++20.
    - **Before C++17:** Only the address or name of a complete object or function with linkage.
    - **Never allowed:** String literals, temporaries, typeid results and __func__.
    - **Subobjects:** Array elements and members became valid arguments in C++20.
  - **auto parameters:** C++17 placeholders deduce the parameter type from the argument.
    - **Type is identity:** X<1> and X<1u> are different specializations.
    - **decltype(auto):** Deduces like decltype, so a parenthesized name can give a reference parameter.
    - **Heterogeneous packs:** template<auto... Vs> can hold values of different types.
  - **Argument equivalence:** [temp.type] decides when two argument lists name the same specialization.
    - **Same type required:** Values must have the same type before they are compared.
    - **Floating point identical:** Identical, not ==, so 0.0 and -0.0 give different specializations.
    - **Classes member-wise:** Class values are equivalent when their subobjects are, recursively.
  - **Template parameter objects:** How class-type parameters exist at run time.
    - **One static object:** A class NTTP names a const object with static storage duration, one per value.
    - **Scalars are prvalues:** &N is ill-formed for template<int N>.
    - **fixed_string idiom:** A class holding a char array, deduced by CTAD, carries text as an argument.
    - **Lambda arguments:** C++20 allows capture-less lambdas as arguments; each lambda is a distinct value.

## Standardese Quiz Questions

### Question 1 [warmup] ([temp.type], [temp.param], [dcl.type.auto.deduct])

What are the values of `A` and `B`?

```cpp
#include <type_traits>

template<auto V> struct X {};

constexpr bool A = std::is_same_v<X<1>, X<2 - 1>>;
constexpr bool B = std::is_same_v<X<1>, X<1u>>;
```

A. Both are true
B. `A` is true, `B` is false
C. `A` is false, `B` is false
D. Ill-formed: `auto` cannot be the type of a template parameter

**Answer (B):** `A` is true, `B` is false

**Why:** `2 - 1` is the `int` value 1, so `A` names the same specialization twice. For `X<1u>` the placeholder deduces `unsigned int`, and template-argument equivalence requires the same type as well as the same value, so `B` is false. `auto` parameters have been allowed since C++17.

### Question 2 [warmup] ([temp.arg.nontype])

Which line is ill-formed in C++23?

```cpp
template<const char* P> struct Tag {};

constexpr char name[] = "hi";

Tag<name> a;      // #1
Tag<"hi"> b;      // #2
Tag<nullptr> c;   // #3
```

A. #1, because `name` has internal linkage
B. #3, because a null pointer is not an object address
C. None of them since C++17
D. #2, because a pointer argument cannot designate a string literal

**Answer (D):** #2, because a pointer argument cannot designate a string literal

**Why:** [temp.arg.nontype] forbids a pointer or reference argument from referring to a string literal, a temporary, a `typeid` result or `__func__`, so #2 is ill-formed. Internal linkage has been enough since C++11 and no linkage is needed since C++17, so #1 is fine, and a null pointer value is a valid argument for a pointer parameter. Pass text through a class-type parameter that stores the characters instead.

### Question 3 [warmup] ([temp.param], [temp.arg.nontype], [over.match.class.deduct])

In C++20, what does this program print?

```cpp
#include <cstddef>
#include <cstdio>

template<std::size_t N> struct fixed_string {
  char data[N];
  constexpr fixed_string(const char (&s)[N]) {
    for (std::size_t i = 0; i < N; ++i) data[i] = s[i];
  }
};

template<fixed_string S> struct Name {
  static constexpr const char* get() { return S.data; }
};

int main() { std::puts(Name<"ok">::get()); }
```

A. `ok`
B. Nothing: ill-formed because string literals cannot be template arguments
C. Nothing: ill-formed because `fixed_string` has a user-provided constructor
D. Undefined behavior: `S.data` dangles after `get` returns

**Answer (A):** `ok`

**Why:** The parameter is a placeholder for a deduced class type, so `fixed_string<3>` is deduced from `"ok"` and the class copies the characters. The string-literal ban applies to pointer and reference arguments, not to a class value built from a literal, and user-provided constructors are fine in a structural type. `S` names a template parameter object with static storage duration, so the returned pointer stays valid.

### Question 4 [tricky] ([temp.type], [temp.param])

In C++20, on an implementation with IEEE 754 `double` (such as any x86-64 or arm64 target), what is the value of `same`?

```cpp
#include <type_traits>

template<double D> struct F {};

constexpr bool same = std::is_same_v<F<0.0>, F<-0.0>>;
```

A. `true`, because `0.0 == -0.0`
B. `false`
C. Ill-formed: floating-point types cannot be template parameters
D. Unspecified

**Answer (B):** `false`

**Why:** For floating-point arguments, [temp.type] requires the values to be identical, not merely equal under `==`. Positive and negative zero compare equal but are different values, so they give two distinct specializations. Floating-point parameters are allowed since C++20, so the third option describes C++17.

### Question 5 [tricky] ([expr.const], [temp.arg.nontype])

In C++20, is this well-formed?

```cpp
template<double D> struct Scale {};

Scale<1> s;
```

A. Well-formed: 1 converts exactly to 1.0
B. Ill-formed: integral-to-floating conversions are not allowed in a converted constant expression
C. Well-formed, but `Scale<1>` and `Scale<1.0>` are different types
D. Ill-formed: floating-point parameters require a floating-point literal with a suffix

**Answer (B):** Ill-formed: integral-to-floating conversions are not allowed in a converted constant expression

**Why:** An NTTP argument must be a converted constant expression of the parameter type, and [expr.const] allows only a short list of conversions: non-narrowing integral conversions and promotions, floating-point promotions and exact floating-point conversions, and a few pointer conversions. A floating-integral conversion is not on the list, even though 1 is exactly representable, so the program is ill-formed. GCC and Clang both reject it; write `Scale<1.0>`.

### Question 6 [tricky] ([temp.param], [temp.type])

In C++20, what does this program print?

```cpp
#include <cstdio>

struct P { int x; };

template<P V> const P* f() { return &V; }
template<P V> const P* g() { return &V; }

int main() {
  std::printf("%d\n", f<P{1}>() == g<P{1}>());
}
```

A. `0`: each function template has its own copy of the argument
B. Ill-formed: a template parameter is a prvalue and has no address
C. Undefined behavior: the pointer dangles after `where` returns
D. `1`

**Answer (D):** `1`

**Why:** A class-type NTTP names a template parameter object of type `const P` with static storage duration, and no two such objects are template-argument-equivalent, so `f<P{1}>` and `g<P{1}>` both refer to the one object for the value `P{1}`. Taking the address is fine because, unlike a scalar NTTP, the name is an lvalue. The prvalue rule in the second option applies to `template<int N>`, where `&N` is ill-formed.

### Question 7 [standardese] ([temp.param], [basic.types.general])

Under C++20 rules, which of these class types can be the type of a non-type template parameter?

```cpp
struct A { int v; constexpr A(int x) : v(x) {} };
class B { int v = 0; public: constexpr B() = default; };
struct C { mutable int v; };
struct D : private A { constexpr D() : A(0) {} };
```

A. Only `A`
B. `A` and `B`
C. `A` and `D`
D. All four, since each is a literal type

**Answer (A):** Only `A`

**Why:** A structural class type must be a literal class whose bases and non-static data members are all public and non-mutable, with structural types. `A` qualifies; its user-provided constexpr constructor does not matter. `B` has a private member, `C` a mutable one, and `D` a private base, so none of them is structural even though all are literal types.

### Question 8 [standardese] ([temp.arg.nontype])

In which standard versions is `Slot<&arr[1]>` a valid template argument?

```cpp
template<int* P> struct Slot {};
int arr[3];

Slot<&arr[1]> s;
```

A. C++20 and later
B. C++17 and later
C. C++11 and later
D. None: array elements can never be template arguments

**Answer (A):** C++20 and later

**Why:** Before C++17 a pointer argument had to be the address of a complete object with linkage, which an array element is not. C++17 accepted any constant expression but still excluded pointers to subobjects. C++20 lifted that exclusion, keeping only the bans on temporaries, string literals, `typeid` results, `__func__` and their subobjects, so the argument is valid from C++20 on.

# Partial ordering of templates

> When several function templates or class template partial specializations match equally well, the compiler picks the most specialized one by deducing each template against a synthesized instance of the other. Constraints, forwarding references, packs and C++20 rewritten operators each add a rule on top, and some pairs stay ambiguous no matter what.

- **Source:** C++ Atlas (https://cppatlas.com/topics/partial-ordering-of-templates)
- **Track:** Templates
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [temp.func.order] (https://eel.is/c++draft/temp.func.order), [temp.deduct.partial] (https://eel.is/c++draft/temp.deduct.partial), [temp.spec.partial.order] (https://eel.is/c++draft/temp.spec.partial.order), [temp.spec.partial.general] (https://eel.is/c++draft/temp.spec.partial.general), [over.match.best.general] (https://eel.is/c++draft/over.match.best.general), [over.ics.rank] (https://eel.is/c++draft/over.ics.rank), [temp.constr.order] (https://eel.is/c++draft/temp.constr.order), [over.match.oper] (https://eel.is/c++draft/over.match.oper), [temp.expl.spec] (https://eel.is/c++draft/temp.expl.spec)
- **cppreference links:** [Function template (partial ordering)](https://en.cppreference.com/w/cpp/language/function_template), [Partial template specialization](https://en.cppreference.com/w/cpp/language/partial_specialization), [Overload resolution](https://en.cppreference.com/w/cpp/language/overload_resolution), [Constraints and concepts](https://en.cppreference.com/w/cpp/language/constraints)
- **Prerequisites:** template-argument-deduction, overload-resolution, concepts-and-constraints, template-instantiation-and-specialization

## The one idea

Overload resolution first compares conversion sequences. Partial ordering only runs when two candidates are function template specializations that convert every argument equally well. It then asks a question about the templates themselves, not about the call: which one accepts a strict subset of what the other accepts?

The compiler answers that question mechanically. It invents a unique type for each template parameter of one template, substitutes them in, and tries to deduce the other template from the result. If `f(T*)` with an invented `U1` gives `f(U1*)`, the template `f(T)` can be deduced from it, with `T = U1*`. In the other direction `f(T*)` cannot be deduced from `f(U1)`. So every argument list `f(T*)` accepts is also accepted by `f(T)`, but not the other way round, and `f(T*)` is more specialized.

> **Mental model.** "More specialized" means "its patterns are an instance of the other's". Pretend to call each template with the other's most general argument types; the one that cannot swallow the other's is the winner.

## Where ordering sits in overload resolution

[over.match.best.general] lists the tie-breakers in order. A viable function is better than another if it has a better conversion sequence for some argument and no worse one for any other. Only when the conversions are equal do these apply, in this order: a non-template beats a template specialization; then the specialization of the more specialized template wins; then, for non-template functions with the same parameter types, the more constrained one wins; and later still, a non-rewritten candidate beats a rewritten one, and a non-reversed one beats a reversed one.

That order explains the classic surprises. A template with an exact match beats a non-template that needs a promotion, because conversions are compared first.

```cpp
#include <cstdio>

void f(int) { std::puts("non-template"); }
template<class T> void f(T) { std::puts("template"); }

int main() {
  f(1);    // non-template: equal conversions, non-template wins the tie
  f('a');  // template: T = char is an exact match, int needs a promotion
}
```

## The deduction procedure

[temp.deduct.partial] fixes which types take part. In a call, only parameters for which the call has explicit arguments are used, so default arguments and unmatched trailing packs do not count. For taking the address of a function template the whole function type is used, and for conversion function templates the return types are used.

Before deducing, references are stripped from both sides and then top-level cv-qualifiers, with one record kept: if both sides were references, the compiler remembers which was an lvalue reference and which was more cv-qualified, for a tie-break described below. Each template is then deduced against the other's synthesized parameter types. A template is at least as specialized as another if deduction succeeds for every considered type; it is more specialized if, in addition, the reverse fails for at least one.

```cpp
#include <cstdio>

template<class T> void b(T)        { std::puts("b(T)"); }
template<class T> void b(T*)       { std::puts("b(T*)"); }
template<class T> void b(const T*) { std::puts("b(const T*)"); }

int main() {
  int i = 0; const int ci = 0;
  b(&i);   // b(T*): b(const T*) needs a qualification conversion and loses
           // on conversions; b(T*) beats b(T) by partial ordering
  b(&ci);  // b(const T*): all three are exact, and it is the most specialized
}
```

Ordering is pairwise, and the winner must be more specialized than every other candidate. When neither of a pair is more specialized, and nothing earlier separated them, the call is ambiguous. Templates that each specialize a different parameter are the textbook case.

```cpp
template<class T> void g(T, int*) {}
template<class T> void g(int*, T) {}

void use(int* p) {
  // g(p, p);  // error: ambiguous; each template is more specialized in one position
  (void)p;
}
```

An explicit specialization is not a candidate in any of this. It is attached to whichever primary template partial ordering selected at the point where the specialization was declared, and it is used only if overload resolution picks that template.

```cpp
#include <cstdio>

template<class T> void h(T)       { std::puts("h(T)"); }
template<> void h<>(int*)         { std::puts("h(T) specialized for int*"); }
template<class T> void h(T*)      { std::puts("h(T*)"); }

int main() { int i = 0; h(&i); }  // prints h(T*): the specialization belongs to h(T)
```

## References, forwarding references and packs

When deduction succeeds in both directions and both original types were references, [temp.deduct.partial] adds two tie-breaks. A parameter whose argument side was an lvalue reference is more specialized than one that was an rvalue reference, and the more cv-qualified reference is more specialized. This is why `f(T&)` beats `f(T&&)` for an lvalue, and `f(const T&)` beats `f(T&&)` for a const lvalue.

It does not mean `const T&` beats a forwarding reference in general. For a non-const lvalue, `f(T&&)` deduces `T = int&` and binds `int&`, which [over.ics.rank] prefers to binding `const int&`. The conversion comparison decides, and partial ordering never runs. The topic on forwarding references covers why this makes forwarding constructors hijack copy construction.

```cpp
#include <cstdio>

template<class T> void c(T&)       { std::puts("c(T&)"); }
template<class T> void c(T&&)      { std::puts("c(T&&)"); }
template<class T> void d(const T&) { std::puts("d(const T&)"); }
template<class T> void d(T&&)      { std::puts("d(T&&)"); }

int main() {
  int i = 0; const int ci = 0;
  c(i);    // c(T&): lvalue-reference tie-break
  d(ci);   // d(const T&): both bind const int&, ordering prefers it
  d(i);    // d(T&&): binding int& is a better conversion than const int&
}
```

Packs are handled by the same deduction. `f(T)` is more specialized than `f(Ts...)`, because `Ts...` can be deduced from `U1` but `T` cannot be deduced from a pack expansion. There is one extra rule: if the two templates tie and one has a trailing parameter pack while the other has no parameter in that position, the one without the pack wins. That makes `f(T)` beat `f(T, Ts...)` for a single argument, a resolution of CWG 1395 that GCC and Clang both implement.

```cpp
#include <cstdio>

template<class T> void e(T)                 { std::puts("e(T)"); }
template<class T, class... Ts> void e(T, Ts...) { std::puts("e(T, Ts...)"); }

int main() {
  e(1);     // e(T): the empty pack loses the tie
  e(1, 2);  // e(T, Ts...): the only viable candidate
}
```

> **Pitfall.** Ordering only considers the parameters the call supplies. `template<class T> void f(T, int = 0)` and `template<class T> void f(T*)` called with one pointer argument are compared on their first parameters alone, so `f(T*)` wins even though the two signatures look incomparable.

## Constraints as the last word

C++20 adds constraints to the picture, though the subject of how constraints subsume each other belongs to the concepts topic. [temp.func.order] says that when deduction succeeds in both directions, and the two templates have equivalent template parameter lists and the same function parameter types after substitution, the more constrained one is more specialized.

The precondition is easy to miss. Constraints only break ties between templates that are otherwise the same shape. Change the parameter from `T` to `const T&` in one of them and the constraint is never consulted.

```cpp
#include <concepts>

template<std::integral T> void k(T) {}
template<class T> void k(T) {}          // same shape: the constrained one wins

template<std::integral T> void m(T) {}
template<class T> void m(const T&) {}   // different parameter types

void use() {
  k(1);       // OK: calls the std::integral overload
  // m(1);    // error: ambiguous; the constraint is not considered
}
```

Subsumption works only through concepts. Two `requires std::is_integral_v<T>` clauses written in different declarations are different atomic constraints, so adding `&& std::is_signed_v<T>` to one of them does not make it more constrained, and the call is ambiguous. The same comparison of constraints also breaks ties between non-template member functions of a class template, such as `void f() requires std::integral<T>` beside a plain `void f()`.

## Ordering class template partial specializations

[temp.spec.partial.order] reuses the function machinery. Each partial specialization is rewritten as a function template with the same template parameters and one function parameter whose type is the specialization's argument list, such as `void p(S<T*>)`. The partial specialization whose function is more specialized wins. If no partial specialization matches, the primary template is used.

The rewriting means the same ambiguities apply. `S<T, int>` and `S<int, T>` both match `S<int, int>`, neither is more specialized, and using `S<int, int>` is ill-formed, while `S<int, long>` and `S<long, int>` are fine. [temp.spec.partial.general] also requires every partial specialization to be more specialized than the primary template; a "specialization" that merely restates the primary's parameters, or that is less constrained, is an error.

```cpp
template<class T, class U> struct S { static constexpr int v = 0; };
template<class T> struct S<T, int> { static constexpr int v = 1; };
template<class T> struct S<int, T> { static constexpr int v = 2; };
template<class T> struct S<T*, T*> { static constexpr int v = 3; };

static_assert(S<long, int>::v == 1 && S<int, long>::v == 2);
static_assert(S<char*, char*>::v == 3);
// S<int, int>::v;  // error: ambiguous partial specializations
```

## Reversed and rewritten operator candidates

C++20 makes `a == b` also consider `b == a`, and `a < b` consider `(a <=> b) < 0` and `0 < (b <=> a)`. The rewritten and reversed candidates join ordinary overload resolution, and the tie-breaks prefer the ordinary candidate only after everything else, including the template rules, has failed to separate them. When a reversed candidate is a template, [temp.func.order] reverses its parameter order before partial ordering.

The ordering of tie-breakers has a visible effect. A non-template beats a template before rewriting is considered, so a reversed non-template candidate beats a non-reversed template.

```cpp
#include <cstdio>

struct X {}; struct Y {};
template<class T, class U> bool operator==(const T&, const U&) {
  std::puts("generic"); return true;
}
bool operator==(const Y&, const X&) { std::puts("Y == X"); return true; }

int main() { X x; Y y; (void)(x == y); }  // prints Y == X, via the reversed candidate
```

> **Standardese.** By the letter of [over.match.best.general], a member `bool operator==(const S&)` that is not `const` makes `s1 == s2` ambiguous with its own reversed form, because each candidate binds one operand better. GCC and Clang accept it with a warning and pick the non-reversed candidate. Declare comparison members `const` and the question never arises.

## What to remember

- Partial ordering runs only after conversion sequences tie, and it compares templates, not calls.
- A non-template beats a template specialization on a tie, but a template with a better conversion beats a non-template.
- The procedure synthesizes unique types for one template and deduces the other from them, in both directions.
- In a call, only parameters with explicit arguments take part; default arguments and empty packs do not.
- Explicit specializations never compete; they belong to the primary template chosen where they were declared.
- `T&` beats `T&&` for lvalues and `const T&` beats `T&&` for const lvalues, but for a non-const lvalue `T&&` wins on conversions.
- Constraints only order templates with equivalent template parameters and parameter types, and subsumption needs named concepts.
- Class partial specializations are ordered by rewriting them as function templates; ambiguity makes the use ill-formed.
- Rewritten and reversed operator candidates lose ties only after the template tie-breakers, so a reversed non-template can beat a template.

## Concept Map Outline

- **Partial ordering:** How the compiler picks the most specialized template when conversions tie.
  - **Place in overload resolution:** A tie-breaker that runs only after conversion sequences fail to separate candidates.
    - **Conversions first:** f('a') picks a template with T = char over f(int), which needs a promotion.
    - **Non-template wins ties:** With equal conversions a non-template beats any template specialization.
    - **Tie-breaker order:** Non-template, then more specialized, then more constrained, then non-rewritten, then non-reversed.
  - **The procedure:** Synthesize unique types for one template and deduce the other from it, both ways.
    - **Types considered:** In a call, only parameters with explicit arguments; default arguments are ignored.
    - **Adjustments:** References and then top-level cv are stripped before deducing.
    - **More specialized:** Deduction succeeds one way for all types and fails the other way for some.
    - **Ambiguity:** g(T, int*) and g(int*, T) each win one position, so g(p, p) is ambiguous.
  - **References and packs:** Extra tie-breaks when deduction succeeds in both directions.
    - **Lvalue beats rvalue:** f(T&) is more specialized than f(T&&) for an lvalue argument.
    - **More cv wins:** const T& beats T&& for a const lvalue, after both bind const int&.
    - **Forwarding wins conversions:** For a non-const lvalue T&& binds int&, which beats const int& before ordering runs.
    - **Trailing pack loses:** On a tie, f(T) beats f(T, Ts...) because of the empty pack (CWG 1395).
  - **Constraints:** C++20 lets the more constrained template win, under conditions.
    - **Same shape required:** Only templates with equivalent template parameters and parameter types are compared by constraints.
    - **Concepts subsume:** Repeated requires is_integral_v<T> clauses are different atomic constraints and never subsume.
    - **Non-template members:** Constraints also order non-template members of class templates with equal parameters.
  - **Specializations:** Explicit and partial specializations use the same ordering differently.
    - **Explicit ones never compete:** They attach to the primary template chosen where they are declared.
    - **Class partial ordering:** Each partial specialization is rewritten as a function template taking S<args>.
    - **Ambiguous use ill-formed:** S<T, int> and S<int, T> both match S<int, int>, so that use is an error.
    - **Must beat primary:** A partial specialization must be more specialized than the primary template.
  - **Rewritten operators:** C++20 adds reversed and rewritten comparison candidates.
    - **Reversed parameter order:** A reversed template candidate is ordered with its parameters reversed.
    - **Late tie-breaker:** A reversed non-template still beats a non-reversed template.
    - **Non-const member ==:** Ambiguous by the letter of C++20; GCC and Clang accept it with a warning.

## Standardese Quiz Questions

### Question 1 [warmup] ([over.match.best.general], [over.ics.rank])

What does this program print?

```cpp
#include <cstdio>

void f(int) { std::puts("non-template"); }
template<class T> void f(T) { std::puts("template"); }

int main() { f('a'); }
```

A. `non-template`, because non-templates are always preferred
B. Nothing: the call is ambiguous
C. `template`
D. `non-template`, because `char` promotes to `int`

**Answer (C):** `template`

**Why:** Conversion sequences are compared before any tie-breaker. The template deduces `T = char`, an exact match, while `f(int)` needs an integral promotion, so the template specialization is the better candidate. The preference for non-templates only applies when the conversions are equally good, as they would be for `f(1)`.

### Question 2 [warmup] ([temp.func.order], [temp.deduct.partial])

What does this program print?

```cpp
#include <cstdio>

template<class T> void b(T)  { std::puts("b(T)"); }
template<class T> void b(T*) { std::puts("b(T*)"); }

int main() {
  int i = 0;
  b(&i);
}
```

A. `b(T)`, because it was declared first
B. Nothing: the call is ambiguous because both are exact matches
C. `b(T*)`
D. `b(T)`, because `T = int*` needs no adjustment

**Answer (C):** `b(T*)`

**Why:** Both candidates are exact matches, so partial ordering decides. `b(T)` can be deduced from the synthesized `b(U*)`, but `b(T*)` cannot be deduced from `b(U)`, so `b(T*)` is more specialized and is chosen. Exact matches on both sides are precisely the situation partial ordering exists to resolve, so the call is not ambiguous; declaration order plays no role.

### Question 3 [warmup] ([temp.spec.partial.match], [temp.spec.partial.order])

Which line makes this program ill-formed?

```cpp
template<class T, class U> struct S { static constexpr int v = 0; };
template<class T> struct S<T, int> { static constexpr int v = 1; };
template<class T> struct S<int, T> { static constexpr int v = 2; };

constexpr int a = S<long, int>::v;   // #1
constexpr int b = S<int, long>::v;   // #2
constexpr int c = S<int, int>::v;    // #3
constexpr int d = S<long, long>::v;  // #4
```

A. #3
B. #4, because no partial specialization matches
C. None; #3 uses the primary template when specializations conflict
D. #1 and #2, because the two partial specializations overlap

**Answer (A):** #3

**Why:** Both partial specializations match `S<int, int>`, and rewriting them as function templates `void p(S<T, int>)` and `void p(S<int, T>)` shows neither is more specialized, so #3 is ill-formed. Overlapping specializations are only a problem for arguments they both match, so #1 and #2 are fine. When no partial specialization matches, as in #4, the primary template is used; it is never a fallback for an ambiguity.

### Question 4 [tricky] ([temp.expl.spec], [temp.func.order], [over.match.best.general])

What does this program print?

```cpp
#include <cstdio>

template<class T> void h(T)  { std::puts("h(T)"); }
template<> void h<>(int*)    { std::puts("h<int*>"); }
template<class T> void h(T*) { std::puts("h(T*)"); }

int main() {
  int i = 0;
  h(&i);
}
```

A. `h<int*>`, because an exact explicit specialization beats any template
B. `h(T*)`
C. `h(T)`
D. Nothing: the specialization makes the call ambiguous

**Answer (B):** `h(T*)`

**Why:** When the explicit specialization is declared, only `h(T)` exists, so it specializes `h(T)` with `T = int*`. Explicit specializations do not take part in overload resolution; the primary templates do, and `h(T*)` is more specialized than `h(T)`, so `h<int>(int*)` from the second template is called. Declaring the specialization after both templates would attach it to `h(T*)` instead and print `h<int*>`.

### Question 5 [tricky] ([over.ics.rank], [temp.deduct.partial], [temp.deduct.call])

What does this program print?

```cpp
#include <cstdio>

template<class T> void d(const T&) { std::puts("const T&"); }
template<class T> void d(T&&)      { std::puts("T&&"); }

int main() {
  int i = 0;
  const int ci = 0;
  d(i);
  d(ci);
}
```

A. `const T&` then `const T&`
B. `T&&` then `T&&`
C. `const T&` then `T&&`
D. `T&&` then `const T&`

**Answer (D):** `T&&` then `const T&`

**Why:** For `d(i)`, the forwarding reference deduces `T = int&` and binds `int&`, which is a better reference binding than `const int&`, so conversions decide before partial ordering runs. For `d(ci)`, both bind `const int&` equally, so partial ordering applies, and its reference tie-break makes `const T&` more specialized than `T&&`. The tempting `const T&` twice assumes ordering always prefers the more specific-looking parameter.

### Question 6 [tricky] ([temp.func.order], [temp.constr.order], [over.match.best.general])

Which call is ill-formed?

```cpp
#include <concepts>

template<std::integral T> void k(T) {}
template<class T> void k(T) {}

template<std::integral T> void m(T) {}
template<class T> void m(const T&) {}

int main() {
  k(1);  // #1
  m(1);  // #2
}
```

A. #1: two templates with the same signature cannot be overloaded
B. Neither: the constrained template wins both calls
C. #2: the call is ambiguous
D. Both

**Answer (C):** #2: the call is ambiguous

**Why:** Constraints only break a tie between templates whose template parameters and function parameter types are equivalent. The two `k` templates have that shape, and they are distinct declarations because their constraints differ, so the constrained one wins #1. For `m`, `T` and `const T&` deduce from each other in both directions, but the parameter types differ, so [temp.func.order] never consults the constraint, and the equal conversions leave #2 ambiguous, which makes the program ill-formed.

### Question 7 [standardese] ([temp.deduct.partial], [temp.func.order])

With the resolution of CWG 1395 applied, as in current GCC and Clang, what does this print?

```cpp
#include <cstdio>

template<class T> void e(T) { std::puts("e(T)"); }
template<class T, class... Ts> void e(T, Ts...) { std::puts("e(T, Ts...)"); }

int main() { e(1); }
```

A. `e(T, Ts...)`, because it is the more general template
B. `e(T)`
C. Nothing: the call is ambiguous
D. Nothing: a pack cannot be empty in a call

**Answer (B):** `e(T)`

**Why:** In a call, only parameters with arguments are compared, so both templates are compared on their first parameter alone and tie. [temp.deduct.partial] then says that if one template has a trailing parameter pack and the other has no corresponding parameter, the one without the pack is more specialized, so `e(T)` wins. Before that rule the call was ambiguous, which is what older compilers reported.

### Question 8 [standardese] ([over.match.best.general], [over.match.oper])

In C++20, what does this program print?

```cpp
#include <cstdio>

struct X {};
struct Y {};

template<class T, class U> bool operator==(const T&, const U&) {
  std::puts("generic");
  return true;
}
bool operator==(const Y&, const X&) {
  std::puts("Y == X");
  return true;
}

int main() {
  X x; Y y;
  (void)(x == y);
}
```

A. `generic`, because non-reversed candidates are preferred
B. Nothing: the call is ambiguous
C. `Y == X`
D. Nothing: ill-formed because a reversed candidate cannot be selected when a direct one is viable

**Answer (C):** `Y == X`

**Why:** Both candidates bind each operand to a const reference of its exact type, so conversions tie. [over.match.best.general] applies the "non-template beats template specialization" tie-break before the "non-rewritten beats rewritten" one, so the reversed non-template `operator==(const Y&, const X&)` wins. The preference for non-reversed candidates is real but comes later in the list, so it never gets a say here.

---

# Track: Exceptions and error handling

Stack unwinding, exception-safety guarantees and value-based error handling with expected.

# Exceptions and stack unwinding

> A throw creates an exception object in special storage, searches outward for the first handler whose type matches under a short list of rules, and destroys every automatic object on the way. When no handler matches, std::terminate runs, and whether anything was unwound first is up to the implementation.

- **Source:** C++ Atlas (https://cppatlas.com/topics/exceptions-and-stack-unwinding)
- **Track:** Exceptions and error handling
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [except.pre] (https://eel.is/c++draft/except.pre), [except.throw] (https://eel.is/c++draft/except.throw), [except.ctor] (https://eel.is/c++draft/except.ctor), [except.handle] (https://eel.is/c++draft/except.handle), [except.terminate] (https://eel.is/c++draft/except.terminate), [except.uncaught] (https://eel.is/c++draft/except.uncaught), [propagation] (https://eel.is/c++draft/propagation), [except.nested] (https://eel.is/c++draft/except.nested)
- **cppreference links:** [Exceptions](https://en.cppreference.com/w/cpp/language/exceptions), [throw expression](https://en.cppreference.com/w/cpp/language/throw), [Handling exceptions (catch)](https://en.cppreference.com/w/cpp/language/catch), [try block](https://en.cppreference.com/w/cpp/language/try), [std::terminate](https://en.cppreference.com/w/cpp/error/terminate), [std::exception_ptr](https://en.cppreference.com/w/cpp/error/exception_ptr), [std::nested_exception](https://en.cppreference.com/w/cpp/error/nested_exception), [std::uncaught_exceptions](https://en.cppreference.com/w/cpp/error/uncaught_exception)
- **Prerequisites:** raii-and-resource-management, inheritance-and-virtual-functions

## The one idea

A `throw` does three separate things. It creates an **exception object**, a fresh object whose type is the static type of the operand. It then searches the dynamically enclosing `try` blocks, innermost first, for a handler whose type matches that object. Finally, if a handler is found, it **unwinds** the stack to that handler, destroying every automatic object whose scope is being left, and enters the handler.

Almost every surprise comes from forgetting that these are separate. The handler you write receives the exception object, not your operand. Matching ignores the conversions you would expect in a function call. And unwinding is only promised if a handler is actually found.

> **Mental model.** Throwing copies your operand into a hidden object. Catch clauses are tried top to bottom with a much stricter notion of "fits" than overload resolution. Destructors run on the way out only once a match is known to exist.

## The exception object and where it lives

The exception object is copy-initialized from the operand. Its type is the operand's static type with top-level cv-qualifiers removed and arrays and functions decayed to pointers, so `throw "abc"` throws a `const char*`. Throwing through a `Base&` that refers to a `Derived` throws a `Base`, sliced.

The storage is allocated in an unspecified way, and the standard says only that it is never obtained from the global allocation functions. Itanium-ABI implementations such as GCC and Clang use a runtime allocator with an emergency pool, so an out-of-memory condition can still be reported. The object lives until the last active handler for it exits by any means other than rethrowing, or until the last `std::exception_ptr` referring to it is destroyed, whichever is later.

The type must be complete, must not be abstract, and since the resolution of CWG 1863 it must be copy-constructible from a `const` lvalue, because `std::current_exception` may need to copy it. GCC 16 and Clang 21 do not diagnose a move-only exception type, so this is a rule that compilers happen not to enforce, not one you can rely on being harmless.

```cpp
#include <cstdio>

struct Base { virtual const char* name() const { return "Base"; } virtual ~Base() = default; };
struct Derived : Base { const char* name() const override { return "Derived"; } };

void rethrow_sliced(Base& b) { throw b; }   // exception object has type Base

int main() {
  Derived d;
  try { rethrow_sliced(d); }
  catch (Derived&) { std::puts("Derived"); }
  catch (Base& b)  { std::puts(b.name()); }   // prints Base
}
```

## How a handler matches

Handlers of a `try` block are examined in the order they appear, and the first match wins, even if a later one would fit better. For an exception object of type `E`, a handler of type `T`, `const T`, `T&` or `const T&` matches when:

- `T` and `E` are the same type, ignoring top-level cv-qualification;
- `T` is an unambiguous public base class of `E`;
- `T` is a pointer or pointer-to-member type, the handler is `T` or `const T&` (not a plain non-const reference), and `E` converts to `T` by a standard pointer conversion, a qualification conversion or a function pointer conversion; or
- `T` is a pointer or pointer-to-member type and `E` is `std::nullptr_t`.

That is the whole list. There are no integral promotions, no arithmetic conversions and no user-defined conversions.

```cpp
#include <cstdio>

struct Base {};
struct Hidden : private Base {};

int main() {
  try { throw 42; }
  catch (long)   { std::puts("long"); }      // not taken: no int -> long here
  catch (...)    { std::puts("other"); }     // prints other

  try { throw Hidden{}; }
  catch (Base&)  { std::puts("base"); }      // not taken: Base is a private base
  catch (...)    { std::puts("other"); }     // prints other

  try { throw nullptr; }
  catch (int*)   { std::puts("int*"); }      // taken: nullptr_t matches any pointer handler
}
```

A `catch (...)` handler must be the last one in its `try` block, or the program is ill-formed. Putting a derived-class handler after a base-class handler is legal but dead code, and both GCC and Clang warn about it.

> **Pitfall.** GCC 16 and Clang 21 both let a handler of type `void*&` catch a thrown `int*`, which the standard does not allow: pointer conversions apply only to by-value and `const&` handlers, because a non-const reference to `void*` cannot refer to an `int*` object. Write pointer handlers by value if you ever need them.

### By value or by reference

A handler parameter is initialized from the exception object, which is an lvalue. Catching by value therefore copies, slices polymorphic exceptions to the handler's type, and runs a copy constructor that, if it throws, calls `std::terminate`. Catching by reference binds directly to the exception object, so virtual calls see the dynamic type and modifications are visible if the exception is rethrown. Catch class types by `const&`, or by `&` if you intend to modify them.

## Rethrowing: `throw;` versus `throw e;`

A bare `throw;` rethrows the exception object currently being handled. It does not copy, it does not slice, and it keeps the dynamic type. Writing `throw e;` creates a brand new exception object copy-initialized from `e`, using `e`'s static type.

```cpp
#include <cstdio>
#include <stdexcept>

int main() {
  try {
    try { throw std::out_of_range("index"); }
    catch (const std::exception& e) { throw; }   // same out_of_range object
  } catch (const std::out_of_range&) { std::puts("out_of_range"); }

  try {
    try { throw std::out_of_range("index"); }
    catch (const std::exception& e) { throw e; } // new std::exception, sliced
  } catch (const std::out_of_range&) { std::puts("out_of_range");
  } catch (const std::exception&)    { std::puts("exception"); }   // prints exception
}
```

A bare `throw;` evaluated when no exception is being handled calls `std::terminate`. It may appear in any function called from a handler, not only lexically inside one, which makes the "Lippincott function" idiom possible: a single function that rethrows and translates every exception type into an error code.

## Stack unwinding and function-try-blocks

Once a handler is found, control passes to it and every automatic object constructed since its `try` block was entered is destroyed in reverse order of construction. The same applies inside constructors: if a constructor throws, the fully constructed bases and members of that object are destroyed, but the object's own destructor never runs, because its lifetime never began. If the object was created by a `new` expression, the matching deallocation function is called. A delegating constructor is the exception: once the target constructor has finished, the object exists, and its destructor is called.

During unwinding, `std::uncaught_exceptions()` counts exceptions that have been thrown but whose handler has not yet been entered. A destructor that records the count at construction and compares it at destruction can tell whether it is running because of an exception, which is how scope guards decide between commit and rollback. The older `std::uncaught_exception()` returned a `bool` and could not tell nested cases apart; it was deprecated in C++17 and removed in C++20.

A **function-try-block** wraps an entire function body, including a constructor's member initializer list, in a `try`. It is the only way to see an exception thrown by a base or member initializer.

```cpp
#include <cstdio>
#include <stdexcept>

struct Member { Member() { throw std::runtime_error("member"); } };

struct Holder {
  Member m;
  Holder() try : m() {
  } catch (const std::exception& e) {
    std::printf("saw %s\n", e.what());
  }   // flowing off the end rethrows: Holder cannot be half-built
};

int main() {
  try { Holder h; } catch (const std::exception&) { std::puts("still thrown"); }
}
```

> **Standardese.** [except.handle] says that if control reaches the end of a handler of a constructor's or destructor's function-try-block, the current exception is rethrown. Referring to a non-static member or base of the object inside such a handler is undefined behavior, because those subobjects have already been destroyed.

For an ordinary function, flowing off the end of a function-try-block handler is like flowing off the end of the body: fine for `void`, undefined behavior for a function that should return a value, and an implicit `return 0;` in `main`.

## When `std::terminate` is called

The standard lists the situations in [except.terminate]. The ones you meet in practice are:

- no matching handler exists for a thrown exception;
- an exception tries to leave a function with a non-throwing exception specification, including any destructor not explicitly marked `noexcept(false)`;
- a function called directly by the unwinding machinery, such as a destructor of a local being destroyed or the copy constructor of a by-value handler parameter, exits via an exception;
- `throw;` is evaluated with no exception being handled;
- an exception escapes the initialization or destruction of a variable with static or thread storage duration, a function registered with `std::atexit`, or the initial function of a `std::thread`.

When no matching handler is found, it is **implementation-defined** whether the stack is unwound before `std::terminate` is called. GCC and Clang with the Itanium ABI search for a handler first and do not unwind at all if none exists, so destructors of locals in `main` do not run. That is why an RAII object can never be relied on to flush a log on an uncaught exception, and why a `catch (...)` in `main` matters.

```cpp
#include <cstdio>

struct Flush { ~Flush() { std::puts("flushed"); } };

int main() {
  Flush f;
  throw 1;   // std::terminate; with GCC and Clang, "flushed" is never printed
}
```

## Carrying exceptions across boundaries

`std::exception_ptr` is a shared-ownership handle to an exception object. `std::current_exception()` inside a handler returns one referring to the exception being handled, or to a copy of it, which is the reason for the copy-constructibility rule. `std::rethrow_exception(p)` throws that object again somewhere else, for example on another thread. `std::promise::set_exception` and `std::async` use exactly this mechanism, as described in the futures-promises-and-async topic.

`std::nested_exception` captures the current exception when it is constructed. `std::throw_with_nested(e)` throws an object of a type derived from both `e`'s type and `std::nested_exception`, so a high-level error can carry its low-level cause. `std::rethrow_if_nested(e)` rethrows that cause if `e` has one, and otherwise does nothing.

```cpp
#include <cstdio>
#include <exception>
#include <stdexcept>

int main() {
  try {
    try { throw std::runtime_error("disk full"); }
    catch (...) { std::throw_with_nested(std::logic_error("save failed")); }
  } catch (const std::logic_error& e) {
    std::puts(e.what());                            // save failed
    try { std::rethrow_if_nested(e); }
    catch (const std::runtime_error& cause) { std::puts(cause.what()); }   // disk full
  }
}
```

## What to remember

- A `throw` copy-initializes an exception object of the operand's static type; throwing through a base reference slices.
- Handlers are tried in order; the first match wins, and `catch (...)` must come last.
- Matching allows exact type, unambiguous public base, pointer and qualification conversions, and `nullptr_t` to pointer; nothing else.
- Catch by reference; by value copies, slices, and can terminate if the copy throws.
- `throw;` rethrows the same object; `throw e;` throws a new, possibly sliced, copy.
- Unwinding destroys automatic objects in reverse order and fully built subobjects of a failing constructor; the failing object's destructor never runs.
- A constructor's function-try-block handler always rethrows when it reaches its end.
- With no matching handler, whether the stack unwinds is implementation-defined, and GCC and Clang do not unwind.
- `exception_ptr`, `throw_with_nested` and `uncaught_exceptions` let exceptions be stored, chained and detected.

## Concept Map Outline

- **Exceptions and stack unwinding:** Throw creates an object, the search finds a handler, unwinding destroys locals on the way.
  - **Exception object:** Copy-initialized from the throw operand, with the operand's static type.
    - **Static type:** Throwing through a Base& throws a sliced Base; arrays decay, so throw "abc" throws const char*.
    - **Unspecified storage:** Allocated in an unspecified way, never by the global allocation functions.
    - **Lifetime:** Lives until the last handler exits without rethrowing and the last exception_ptr to it is gone.
    - **Type requirements:** Complete, not abstract, and copyable from a const lvalue since CWG 1863.
  - **Handler matching:** Handlers are tried in order of appearance; the first match wins.
    - **Allowed matches:** Same type, unambiguous public base, pointer or qualification conversion, nullptr_t to pointer.
    - **No other conversions:** No promotions, arithmetic or user-defined conversions: catch (long) misses an int.
    - **catch (...) last:** A catch-all that is not the last handler makes the program ill-formed.
    - **Catch by reference:** By value copies and slices; by reference sees the dynamic type and can modify the object.
  - **Rethrowing:** Two spellings with very different effects.
    - **throw;:** Rethrows the same exception object, keeping its dynamic type; terminates if none is active.
    - **throw e;:** Creates a new exception object of e's static type, slicing derived exceptions.
  - **Stack unwinding:** Automatic objects since the try block are destroyed in reverse order of construction.
    - **Failing constructor:** Built subobjects are destroyed; the object's own destructor never runs.
    - **Function-try-block:** Catches initializer exceptions; a constructor's handler always rethrows at its end.
    - **uncaught_exceptions:** Counts exceptions thrown but not yet caught; lets scope guards detect unwinding.
  - **std::terminate:** Called when exception handling itself cannot continue.
    - **No handler:** Whether the stack is unwound first is implementation-defined; GCC and Clang do not unwind.
    - **noexcept violated:** An exception leaving a non-throwing function, including a default destructor.
    - **Throw during unwinding:** A destructor run by unwinding that exits via an exception terminates the program.
  - **Transporting exceptions:** Library tools to store, move and chain exceptions.
    - **exception_ptr:** current_exception captures, rethrow_exception throws again, even on another thread.
    - **nested_exception:** throw_with_nested attaches the current exception; rethrow_if_nested recovers it.

## Standardese Quiz Questions

### Question 1 [warmup] ([except.handle])

What does this program print?

```cpp
#include <cstdio>

int main() {
  try { throw 42; }
  catch (long)   { std::puts("long"); }
  catch (double) { std::puts("double"); }
  catch (...)    { std::puts("other"); }
}
```

A. `long`
B. `double`
C. `other`
D. Ill-formed: `42` is ambiguous between the `long` and `double` handlers

**Answer (C):** `other`

**Why:** Handler matching does not use integral or floating conversions. An `int` exception object only matches a handler for `int`, a base class (not applicable here), or a pointer type through pointer conversions. Neither `long` nor `double` matches, so `catch (...)` is taken. The tempting `long` answer applies function-call conversion rules, which handlers do not use.

### Question 2 [warmup] ([except.throw])

What does this program print?

```cpp
#include <cstdio>
#include <stdexcept>

int main() {
  try {
    try { throw std::out_of_range("index"); }
    catch (const std::exception& e) { throw e; }
  }
  catch (const std::out_of_range&) { std::puts("out_of_range"); }
  catch (const std::exception&)    { std::puts("exception"); }
}
```

A. `exception`
B. `out_of_range`
C. Both lines
D. Nothing; `std::terminate` is called

**Answer (A):** `exception`

**Why:** `throw e;` creates a new exception object copy-initialized from `e`, and the type of that object is the static type of `e`, which is `std::exception`. The `out_of_range` part is sliced away, so only the second handler matches. A bare `throw;` would have rethrown the original `out_of_range` object and printed `out_of_range`.

### Question 3 [warmup] ([except.handle], [dcl.init.general])

What does this program print?

```cpp
#include <cstdio>

struct Base { virtual const char* name() const { return "Base"; } virtual ~Base() = default; };
struct Derived : Base { const char* name() const override { return "Derived"; } };

int main() {
  try { throw Derived{}; }
  catch (Base b) { std::puts(b.name()); }
}
```

A. `Derived`, because the exception object is a `Derived`
B. `Base`
C. Nothing: a `Base` handler does not match a `Derived` exception
D. Undefined behavior

**Answer (B):** `Base`

**Why:** The handler matches because `Base` is an unambiguous public base of `Derived`. But a by-value handler parameter is copy-initialized from the exception object, so `b` is a separate `Base` object, sliced, and the virtual call sees its dynamic type `Base`. Catching by `const Base&` would bind to the `Derived` exception object and print `Derived`.

### Question 4 [tricky] ([except.throw], [except.handle])

What does this program print?

```cpp
#include <cstdio>
#include <string>

int main() {
  try { throw "disk full"; }
  catch (const std::string& s) { std::puts("string"); }
  catch (const char* p)        { std::puts("pointer"); }
}
```

A. `string`, because the first handler that can accept the value wins
B. Nothing; `std::terminate` is called because no handler has array type
C. Ill-formed: an array cannot be thrown
D. `pointer`

**Answer (D):** `pointer`

**Why:** The exception object's type is the operand's type with arrays decayed to pointers, so it is `const char*`. Handlers are tried in order, but a handler only matches through the narrow rules of [except.handle], which exclude user-defined conversions such as `std::string`'s converting constructor. The first handler is skipped and the pointer handler is taken.

### Question 5 [tricky] ([except.handle], [except.ctor])

What does this program print?

```cpp
#include <cstdio>
#include <stdexcept>

struct Member { Member() { throw std::runtime_error("m"); } };

struct Holder {
  Member m;
  Holder() try : m() {
  } catch (const std::exception&) {
    std::puts("handler");
  }
};

int main() {
  try { Holder h; std::puts("built"); }
  catch (const std::exception&) { std::puts("outer"); }
}
```

A. `handler` then `outer`
B. `handler` then `built`
C. `outer` only; a function-try-block cannot catch initializer exceptions
D. `handler`, then `std::terminate` is called

**Answer (A):** `handler` then `outer`

**Why:** A constructor's function-try-block does see exceptions from member initializers, so `handler` is printed. When control reaches the end of such a handler, the exception is implicitly rethrown, because the object cannot exist with a member that was never constructed. The outer handler catches it and prints `outer`; `built` is never reached. Swallowing the exception, as the first option assumes, is impossible here.

### Question 6 [tricky] ([except.ctor], [except.terminate])

What happens when this program runs?

```cpp
#include <cstdio>

struct Bad {
  ~Bad() noexcept(false) { throw 2; }
};

int main() {
  try {
    Bad b;
    throw 1;
  } catch (int i) {
    std::printf("caught %d\n", i);
  }
}
```

A. Prints `caught 1`
B. Prints `caught 2`; the newer exception replaces the older one
C. `std::terminate` is called
D. Undefined behavior

**Answer (C):** `std::terminate` is called

**Why:** Throwing `1` finds the handler and starts unwinding, which destroys `b`. The destructor is called directly by the unwinding mechanism and exits via an exception, which is one of the listed cases where `std::terminate` is called. `noexcept(false)` only allows the destructor to throw when no unwinding is in progress; there is no rule that lets one exception replace another.

### Question 7 [standardese] ([except.terminate], [except.handle])

What does the standard say about whether `flushed` is printed?

```cpp
#include <cstdio>

struct Flush { ~Flush() { std::puts("flushed"); } };

int main() {
  Flush f;
  throw 1;
}
```

A. It is always printed: unwinding precedes `std::terminate`
B. It is never printed: `std::terminate` is called before any destructor
C. It is implementation-defined whether the stack is unwound, so it may or may not be printed
D. The program has undefined behavior

**Answer (C):** It is implementation-defined whether the stack is unwound, so it may or may not be printed

**Why:** No handler matches, so `std::terminate` is called, and [except.terminate] makes it implementation-defined whether the stack is unwound first. GCC and Clang search for a handler before unwinding and do not run `~Flush`, which makes "never printed" tempting, but that is a property of those implementations, not a guarantee. The behavior is defined: the program terminates.

### Question 8 [standardese] ([except.throw], [basic.stc.dynamic.allocation])

Which statement about the storage of an exception object does the C++23 standard guarantee?

A. It is obtained from `operator new`, so replacing `operator new` intercepts it
B. It lives in the stack frame of the function that executed the `throw`
C. It has static storage duration, so only one exception can exist at a time
D. It is allocated in an unspecified way, but never by the global allocation functions

**Answer (D):** It is allocated in an unspecified way, but never by the global allocation functions

**Why:** [except.throw] says the memory is allocated in an unspecified way, and [basic.stc.dynamic.allocation] adds that the global allocation functions are not used for it. Implementations typically use a runtime function with an emergency pool so `std::bad_alloc` can still be thrown. The stack-frame answer cannot be right, because the thrower's frame is destroyed during unwinding while the object must survive into the handler, and several exceptions can be alive at once.

# noexcept

> The noexcept specifier is a promise that a function will not let an exception escape, enforced at run time by std::terminate rather than at compile time. The noexcept operator asks whether an expression could throw, and since C++17 the promise is part of the function type.

- **Source:** C++ Atlas (https://cppatlas.com/topics/noexcept)
- **Track:** Exceptions and error handling
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [except.spec] (https://eel.is/c++draft/except.spec), [expr.unary.noexcept] (https://eel.is/c++draft/expr.unary.noexcept), [conv.fctptr] (https://eel.is/c++draft/conv.fctptr), [except.terminate] (https://eel.is/c++draft/except.terminate), [class.dtor] (https://eel.is/c++draft/class.dtor), [dcl.fct.def.default] (https://eel.is/c++draft/dcl.fct.def.default), [res.on.exception.handling] (https://eel.is/c++draft/res.on.exception.handling)
- **cppreference links:** [noexcept specifier](https://en.cppreference.com/w/cpp/language/noexcept_spec), [noexcept operator](https://en.cppreference.com/w/cpp/language/noexcept), [Dynamic exception specification](https://en.cppreference.com/w/cpp/language/except_spec), [std::move_if_noexcept](https://en.cppreference.com/w/cpp/utility/move_if_noexcept), [std::terminate](https://en.cppreference.com/w/cpp/error/terminate)
- **Prerequisites:** exceptions-and-stack-unwinding, copy-and-move

## The one idea

`noexcept` is not a compile-time check. Marking a function `noexcept` does not make the compiler prove that nothing inside it throws. It changes what happens when something does: instead of propagating, the exception reaches the function boundary and `std::terminate` is called.

What makes the promise valuable is that other code can **ask about it at compile time**. The `noexcept` operator turns "can this expression throw?" into a `bool` constant, and the standard library uses that answer to choose faster algorithms, most famously moving rather than copying when a `std::vector` grows.

> **Mental model.** `noexcept` is a contract written in the type system and enforced by termination. Callers read it statically; the runtime enforces it only by ending the program.

## The specifier and the operator

The specifier comes in three spellings. `noexcept` and `noexcept(true)` mean the function has a **non-throwing** exception specification. `noexcept(false)`, or no specifier at all for most functions, means it is **potentially throwing**. The argument must be a contextually converted constant expression of type `bool`, so it may depend on template parameters.

The operator, `noexcept(expr)`, is an unevaluated operand like `sizeof`. It yields `false` if the expression is potentially throwing: if it calls any function, constructor, conversion or destructor that is potentially throwing, or contains a `throw`, a `dynamic_cast` to a reference type that needs a run-time check, or a `typeid` applied to a dereferenced polymorphic glvalue. It yields `true` otherwise. Nothing in the operand runs.

```cpp
int calls = 0;
int count() { return ++calls; }

static_assert(!noexcept(count()));  // count is potentially throwing
static_assert(noexcept(1 + 2));     // no call, cannot throw
static_assert(!noexcept(new int));  // operator new may throw bad_alloc

struct Leaky { ~Leaky() noexcept(false); };
static_assert(!noexcept(Leaky()));  // the temporary's destructor counts
// calls is still 0: the operand was never evaluated
```

The two are combined in the **conditional noexcept** idiom, where the doubled keyword is not a typo. The outer `noexcept` is the specifier, and the inner one is the operator computing its argument.

```cpp
#include <type_traits>
#include <utility>

template <class T>
struct Box {
  T value;
  Box(Box&& other) noexcept(noexcept(T(std::move(other.value))))
      : value(std::move(other.value)) {}

  void swap(Box& o) noexcept(std::is_nothrow_swappable_v<T>) {
    using std::swap;
    swap(value, o.value);
  }
};
```

Traits such as `std::is_nothrow_move_constructible_v` and `std::is_nothrow_invocable_v` are usually clearer than spelling out the expression, and they are implemented with the operator.

## What happens when a noexcept function throws

If an exception tries to leave a function with a non-throwing specification, `std::terminate` is called. The exception is not propagated, and no handler outside the function ever sees it. Handlers inside the function work normally; the boundary only matters for exceptions that would cross it.

> **Standardese.** [except.terminate] makes it implementation-defined whether the stack is unwound, unwound partially, or not unwound at all before `std::terminate` is called in this case. That latitude is what lets compilers omit unwind tables for `noexcept` functions.

The partial case is real. With GCC 16 and Clang 21, the inner frame's locals are destroyed while searching upward, but the `noexcept` frame's own locals are not, because the search stops at its boundary.

```cpp
#include <cstdio>
#include <stdexcept>

struct Note { const char* n; ~Note() { std::fprintf(stderr, "~%s\n", n); } };

void inner() { Note a{"inner"}; throw std::runtime_error("x"); }
void outer() noexcept { Note b{"outer"}; inner(); }

int main() {
  try { outer(); } catch (...) { std::puts("never reached"); }
}
// std::terminate. GCC and Clang print ~inner but not ~outer;
// another implementation could print both or neither.
```

Compilers warn when they can see a `throw` that will always reach a `noexcept` boundary, but the rule is not enforced at compile time, and a call to a potentially-throwing function from a `noexcept` function is always well-formed.

## Implicit noexcept

You get non-throwing specifications without writing them in several places.

- **Destructors.** A destructor declared without a specifier, whether user-written or implicit, has the specification its implicit version would have, which is non-throwing unless some base or member has a potentially-throwing destructor. A deallocation function without a specifier is non-throwing as well.
- **Implicitly declared and defaulted special members.** A default constructor, copy or move constructor, copy or move assignment, or comparison that is implicitly declared or defaulted on its first declaration is non-throwing exactly when every function it would call is non-throwing.
- **Explicitly defaulted with a different specifier.** Since C++20, writing `S(S&&) noexcept(false) = default;` is allowed and the written specification wins. Before C++20, a mismatch on a first declaration made the function deleted.

```cpp
#include <string>
#include <type_traits>

struct Plain { std::string s; };
static_assert(std::is_nothrow_move_constructible_v<Plain>);    // string's move is noexcept
static_assert(!std::is_nothrow_copy_constructible_v<Plain>);   // copying may allocate
static_assert(std::is_nothrow_destructible_v<Plain>);

struct Throws { ~Throws() noexcept(false); };
struct Holds { Throws t; };
static_assert(!std::is_nothrow_destructible_v<Holds>);         // inherited from the member
```

> **Pitfall.** A destructor you write yourself is still implicitly `noexcept`. A `throw` in it, even one meant to report a failed flush, calls `std::terminate` unless you write `noexcept(false)`, and even then it terminates if the destructor runs during unwinding.

## Why move constructors should be noexcept

When `std::vector` reallocates, it must relocate existing elements to the new buffer while keeping the strong guarantee for `push_back`: if something throws, the original vector is untouched. Moving elements destroys that option, because a move that throws halfway leaves some elements moved-from in the old buffer. So the library uses `std::move_if_noexcept`, which moves only when the move constructor is non-throwing or the type cannot be copied, and copies otherwise.

```cpp
#include <cstdio>
#include <vector>

struct Slow {
  Slow() = default;
  Slow(const Slow&) { std::puts("copy"); }
  Slow(Slow&&) { std::puts("move"); }           // potentially throwing
};
struct Fast {
  Fast() = default;
  Fast(const Fast&) { std::puts("copy"); }
  Fast(Fast&&) noexcept { std::puts("move"); }
};

int main() {
  std::vector<Slow> a(1); a.reserve(2);         // prints copy
  std::vector<Fast> b(1); b.reserve(2);         // prints move
}
```

A move constructor that cannot actually throw, but is not declared `noexcept`, silently turns every reallocation into a deep copy. A defaulted move constructor gets this right automatically when all members have non-throwing moves; a hand-written one needs the keyword.

## noexcept in the type system

Since C++17, the exception specification is part of the function type: `void() noexcept` and `void()` are distinct types, as are pointers to them. A **function pointer conversion** goes one way only: a pointer to a `noexcept` function converts to a pointer to the potentially-throwing type, never the reverse.

```cpp
void safe() noexcept;
void risky();

void (*p)() = safe;               // OK: drops the promise
// void (*q)() noexcept = risky;  // ill-formed: would invent a promise

struct S { void m() noexcept; };
void (S::*pm)() = &S::m;          // OK: same rule for member pointers

template <bool B> constexpr bool is_nothrow(void (*)() noexcept(B)) { return B; }
static_assert(is_nothrow(safe) && !is_nothrow(risky));  // B is deducible
```

You still cannot overload on the specification: declaring `void f();` and `void f() noexcept;` is an ill-formed redeclaration, not an overload. Every declaration of a function must agree on its specification, apart from the implicit cases above.

Virtual functions follow the same direction. If a virtual function is non-throwing, every overrider must be non-throwing too, since callers through the base have been promised it. An overrider may add `noexcept` to a potentially-throwing base function.

Lambdas take the specifier after the parameter list, and a captureless `noexcept` lambda converts to a `noexcept` function pointer.

## The road from throw() to noexcept

C++98 had **dynamic exception specifications**, `throw(A, B)`, which listed permitted exception types and called `std::unexpected` at run time if another escaped. They cost run-time checks, did not compose with templates, and nobody could write them correctly for generic code. C++11 deprecated them and added `noexcept`. C++17 removed `throw(A, B)` and `std::unexpected`, and kept `throw()` only as a deprecated synonym for `noexcept(true)`. C++20 removed `throw()` as well, although GCC 16 and Clang 21 still accept it in C++20 and C++23 modes as an extension.

The standard library is deliberately sparing with `noexcept`. Functions with preconditions, such as `std::vector::operator[]`, are not specified `noexcept`, so that a checking implementation could report a violation by throwing. Implementations may add `noexcept` to non-virtual library functions, and libstdc++ and libc++ both mark `operator[]` that way, so `noexcept(v[0])` is `true` in practice and not guaranteed by the standard.

### When to write it

The promise is easy to add and hard to take back. Once callers have written `static_assert(noexcept(f()))`, or chosen an algorithm because a trait said "nothrow", removing the keyword is a breaking change, even if the function's behaviour on success is unchanged. That argues for writing `noexcept` deliberately, in a few places where it pays for itself.

- **Move constructors and move assignment** of types that own resources, because containers and algorithms branch on them.
- **`swap`**, because copy-and-swap and many algorithms are only safe when it cannot fail.
- **Destructors and deallocation** are already non-throwing by default; leave them that way.
- **Hash functions and simple accessors** that genuinely cannot fail, where the promise documents a fact rather than a hope.

Everywhere else, the default of potentially throwing is the honest one. A function that allocates, calls user callbacks, or has preconditions that a future version might want to check by throwing should stay without the keyword, following the same reasoning the library applies to itself. In generic code, prefer a conditional specification computed from the operations you call, so that the promise is exactly as strong as your element types allow and no stronger.

## What to remember

- `noexcept` promises, it does not prove; an escaping exception calls `std::terminate`.
- Whether the stack unwinds before that termination is implementation-defined, and may be partial.
- The `noexcept` operator is unevaluated and asks whether an expression is potentially throwing, including temporaries' destructors and `new`.
- `noexcept(noexcept(expr))` is the conditional idiom; prefer `is_nothrow_*` traits when they fit.
- Destructors and implicit or defaulted special members are `noexcept` whenever what they call is.
- Since C++17 `noexcept` is part of the function type; pointers may drop it but not gain it, and overriders of a `noexcept` virtual must keep it.
- Non-`noexcept` move constructors make `std::vector` copy on reallocation.
- Dynamic exception specifications are gone: `throw(T)` in C++17, `throw()` in C++20.

## Concept Map Outline

- **noexcept:** A no-throw promise in the type system, read at compile time and enforced by std::terminate.
  - **Specifier:** noexcept or noexcept(true) is non-throwing; noexcept(false) or nothing is potentially throwing.
    - **Constant bool argument:** The argument is a constant expression and may depend on template parameters.
    - **Conditional idiom:** noexcept(noexcept(expr)): the outer is the specifier, the inner is the operator.
    - **Not checked statically:** Calling throwing code from a noexcept function is well-formed; compilers only warn.
  - **Operator:** noexcept(expr) is an unevaluated bool constant: false if expr is potentially throwing.
    - **Unevaluated:** Like sizeof, the operand never runs, so side effects never happen.
    - **Hidden calls count:** Temporaries' destructors, conversions and operator new all make the result false.
    - **Traits:** is_nothrow_move_constructible and friends are built on the operator.
  - **Violation:** An exception reaching a noexcept boundary calls std::terminate.
    - **Unwinding unspecified:** Implementation-defined whether the stack is unwound fully, partially or not at all.
    - **Inner handlers work:** Only exceptions that would cross the noexcept boundary terminate.
  - **Implicit noexcept:** Some functions get a non-throwing specification without the keyword.
    - **Destructors:** Non-throwing unless a base or member destructor is potentially throwing.
    - **Defaulted specials:** Non-throwing exactly when every function they would call is non-throwing.
    - **C++20 explicit default:** A written specifier on a defaulted function now wins; before, a mismatch deleted it.
  - **Type system (C++17):** The exception specification is part of the function type.
    - **One-way conversion:** Pointers to noexcept functions convert to plain pointers, never the reverse.
    - **No overloading:** f() and f() noexcept conflict as redeclarations; they cannot overload.
    - **Virtual overrides:** An overrider of a noexcept virtual must be noexcept; adding noexcept is fine.
    - **Deducible:** Templates can deduce B from void(*)() noexcept(B).
  - **Why it matters:** Libraries choose algorithms based on the answer.
    - **move_if_noexcept:** vector reallocation copies copyable elements whose move may throw.
    - **Dynamic specs removed:** throw(T) removed in C++17, throw() removed in C++20.
    - **Narrow contracts:** The standard leaves functions with preconditions potentially throwing; vendors may add noexcept.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.unary.noexcept], [except.spec])

What does this program print?

```cpp
#include <cstdio>

int main() {
  int n = 0;
  bool b = noexcept(n++);
  std::printf("%d %d\n", n, b);
}
```

A. `1 1`
B. `0 0`
C. `1 0`
D. `0 1`

**Answer (D):** `0 1`

**Why:** The operand of the `noexcept` operator is unevaluated, exactly like the operand of `sizeof`, so `n++` never runs and `n` stays 0. A built-in increment calls no function and cannot throw, so the result is `true`, printed as 1. The tempting `1 1` assumes the operand is executed to find out whether it throws.

### Question 2 [warmup] ([conv.fctptr], [except.spec], [dcl.fct])

In C++23, which initialization is ill-formed?

```cpp
void safe() noexcept;
void risky();

void (*a)() = safe;           // #1
void (*b)() noexcept = safe;  // #2
void (*c)() noexcept = risky; // #3
auto d = +[]() noexcept {};   // #4
```

A. #1, because the types differ in their exception specification
B. #3
C. #4, because a lambda's exception specification is not part of its conversion
D. None of them; the exception specification is not part of the type

**Answer (B):** #3

**Why:** Since C++17 `noexcept` is part of the function type, and the function pointer conversion only removes it: a pointer to a non-throwing function converts to a pointer to a potentially-throwing one, which makes #1 fine. #3 would add a promise that `risky` never made, so it is ill-formed. The last option describes C++14, where the specification was not part of the type.

### Question 3 [warmup] ([vector.capacity], [except.spec])

What does this program print?

```cpp
#include <cstdio>
#include <vector>

struct Slow {
  Slow() = default;
  Slow(const Slow&) { std::puts("copy"); }
  Slow(Slow&&) { std::puts("move"); }
};

int main() {
  std::vector<Slow> v(1);
  v.reserve(10);
}
```

A. `copy`
B. `move`
C. Nothing; `reserve` does not touch existing elements
D. Either `copy` or `move`; it is unspecified

**Answer (A):** `copy`

**Why:** `reserve` beyond the current capacity reallocates and must relocate the existing element while keeping the strong guarantee. Because `Slow`'s move constructor is potentially throwing and `Slow` is copyable, the library uses `std::move_if_noexcept`, which yields an lvalue and selects the copy constructor. Marking the move constructor `noexcept` would make it print `move`.

### Question 4 [tricky] ([class.dtor], [except.spec], [except.terminate])

What happens when this program runs?

```cpp
#include <cstdio>

struct Closer {
  ~Closer() { throw 1; }
};

int main() {
  try {
    Closer c;
  } catch (int) {
    std::puts("caught");
  }
}
```

A. Prints `caught`, since no other exception is in flight
B. Ill-formed: a destructor cannot contain a `throw`
C. `std::terminate` is called
D. Undefined behavior

**Answer (C):** `std::terminate` is called

**Why:** A destructor declared without a specifier gets the specification of the implicit destructor, which is non-throwing here because `Closer` has no members or bases with throwing destructors. The exception therefore hits a `noexcept` boundary and `std::terminate` is called. `caught` would only be printed if the destructor were declared `noexcept(false)`; the code is well-formed, and compilers merely warn.

### Question 5 [tricky] ([except.spec], [class.virtual])

Which statement about this code is true?

```cpp
struct Base {
  virtual void a() noexcept;
  virtual void b();
};

struct Derived : Base {
  void a() override;           // #1
  void b() noexcept override;  // #2
};
```

A. Both overrides are well-formed; exception specifications do not affect overriding
B. #1 is well-formed and #2 is ill-formed
C. Both are ill-formed; an overrider must have exactly the same specification
D. #1 is ill-formed and #2 is well-formed

**Answer (D):** #1 is ill-formed and #2 is well-formed

**Why:** Code calling `a()` through a `Base&` has been promised it will not throw, so an overrider of a non-throwing virtual function must itself be non-throwing, and #1 is ill-formed. The reverse is fine: `Derived::b` makes a stronger promise than `Base::b`, which callers through the base can only benefit from. Requiring an exact match, as the third option claims, is stricter than the rule.

### Question 6 [tricky] ([expr.unary.noexcept], [except.spec], [class.temporary])

What is the value of `r`?

```cpp
struct Leaky {
  ~Leaky() noexcept(false);
};

Leaky make() noexcept;

constexpr bool r = noexcept(make());
```

A. `true`, because `make` is `noexcept`
B. `false`
C. Ill-formed: `make` is declared but not defined
D. Ill-formed: the operand of `noexcept` must not create a temporary

**Answer (B):** `false`

**Why:** The operand `make()` is a prvalue that is a full-expression, so a temporary is materialized and destroyed at its end, and that destruction is part of the expression the operator inspects. `~Leaky` is potentially throwing, so the whole expression is potentially throwing and the result is `false`. Looking only at the called function, as the first option does, misses the implicit destructor call. Because the operand is unevaluated, no definition of `make` is needed.

### Question 7 [standardese] ([except.terminate], [except.spec])

An exception thrown in `g` propagates up to `f`, which is declared `noexcept`, with no handler in between. What does the C++23 standard say?

A. The exception propagates to `f`'s caller, because `noexcept` is only an optimization hint
B. `std::terminate` is called after all locals in `g` and `f` have been destroyed
C. `std::terminate` is called; whether the stack is unwound, partially unwound or not unwound first is implementation-defined
D. The behavior is undefined

**Answer (C):** `std::terminate` is called; whether the stack is unwound, partially unwound or not unwound first is implementation-defined

**Why:** [except.terminate] says that when the search for a handler reaches the outermost block of a function with a non-throwing exception specification, `std::terminate` is called, and it is implementation-defined whether the stack is unwound, unwound partially, or not unwound at all. GCC and Clang destroy `g`'s locals but not `f`'s. The second option is tempting because full unwinding is what happens when a handler is found, but no handler is found here. The behavior is defined, just not fully specified.

### Question 8 [standardese] ([except.spec], [diff.cpp14.except])

Compiled as C++17, is this declaration well-formed?

```cpp
void parse() throw(int);
```

A. Ill-formed: dynamic exception specifications with types were removed in C++17
B. Well-formed but deprecated, as in C++11 and C++14
C. Well-formed, and equivalent to `noexcept(false)`
D. Well-formed, and calls `std::unexpected` if anything other than an `int` escapes

**Answer (A):** Ill-formed: dynamic exception specifications with types were removed in C++17

**Why:** C++11 deprecated dynamic exception specifications, and C++17 removed every form except the empty `throw()`, which it kept as a deprecated synonym for `noexcept(true)` until C++20 removed it too. `std::unexpected`, the handler the last option describes, was removed in C++17 along with them. The second option is the C++14 answer.

# Exception-safety guarantees

> How stack unwinding interacts with class invariants: the Abrahams guarantees, noexcept move optimization, copy-and-swap, and unwinding traps.

- **Source:** C++ Atlas (https://cppatlas.com/topics/exception-safety-guarantees)
- **Track:** Exceptions and error handling
- **Estimated reading time:** 10 minutes
- **ISO C++ clauses:** [except] (https://eel.is/c++draft/except), [except.throw] (https://eel.is/c++draft/except.throw), [except.spec] (https://eel.is/c++draft/except.spec), [except.handle] (https://eel.is/c++draft/except.handle), [except.terminate] (https://eel.is/c++draft/except.terminate), [class.dtor] (https://eel.is/c++draft/class.dtor)
- **cppreference links:** [Exceptions](https://en.cppreference.com/w/cpp/language/exceptions), [noexcept specifier](https://en.cppreference.com/w/cpp/language/noexcept_spec), [Throwing exceptions](https://en.cppreference.com/w/cpp/language/throw), [std::move_if_noexcept](https://en.cppreference.com/w/cpp/utility/move_if_noexcept), [std::uncaught_exceptions](https://en.cppreference.com/w/cpp/error/uncaught_exception), [std::terminate](https://en.cppreference.com/w/cpp/error/terminate)
- **Prerequisites:** raii-and-resource-management, copy-and-move

Exceptions separate error detection from error handling across arbitrarily deep call stacks. That flexibility comes with a contract: whenever any expression inside a function throws, every object along the unwound path must remain in a valid state so destructors and enclosing error handlers can reason about what survived.

Exception safety is not a single yes-or-no boolean. David Abrahams formalized four distinct levels of guarantees a function can provide when an operation fails, ranging from zero failure modes down to broken invariants.

## The Abrahams exception-safety hierarchy

Every function in a well-designed C++ codebase sits at a deliberate rung on the exception-safety ladder.

| Guarantee | Observable state after throw | Resource leaks | Typical examples |
| --- | --- | --- | --- |
| Nothrow / Nofail | Operation always succeeds | Never | `swap`, `~T()`, `move` constructors |
| Strong | Identical to state before call | Never | `std::vector::push_back`, copy-and-swap |
| Basic | Valid invariants, unspecified values | Never | Multi-element `std::vector::insert`, `std::sort` |
| None | Broken invariants or leaked handles | Possible | Raw manual `new`/`delete` without RAII |

The **nothrow** (or **nofail**) guarantee promises that an operation never emits an exception—either because nothing inside it can fail, or because failures are absorbed internally. Without a nothrow foundation for `swap`, destructors, and pointer transfers, higher guarantees collapse.

The **strong guarantee** delivers transactional commit-or-rollback semantics: if an exception escapes, the program state rolls back completely as if the call never happened. Standard containers such as `std::vector::push_back` provide this guarantee whenever element relocation does not prevent it.

The **basic guarantee** is the mandatory baseline for almost all production C++ code. An exception may leave mutated objects holding partial updates—a vector might contain half of a batch, or a string might keep its new capacity—yet zero resources leak, class invariants hold, and every surviving object can still be inspected, assigned, or destroyed safely.

> **Mental model.** Strong exception safety is simply a two-phase transaction: perform every allocation or copy that might throw on isolated side state, then commit the result to `this` using exclusively `noexcept` operations.

## Stack unwinding and the exception object

When a `throw expr;` expression executes, the runtime first initializes an **exception object** in unspecified memory (never on the stack frame about to be torn down) by copy- or move-initializing from `expr`, potentially applying copy elision. Control then walks outward through enclosing scopes until a matching `catch` handler is found.

During this **stack unwinding**, automatic objects whose initialization has already completed are destroyed in exact reverse order of construction completion. Partially constructed aggregates and classes receive selective cleanup: if a constructor body or member initializer throws midway through constructing member `b` after member `a` succeeded, the destructor of `a` runs automatically, while the class's own destructor `~Class()` does **not** run because the object never finished beginning its lifetime.

> **Standardese.** Under `[except.throw]` and `[except.terminate]`, if no matching handler exists anywhere on the call stack, or if unwinding encounters a function marked `noexcept(true)`, the implementation calls `std::terminate()`—and it is implementation-defined whether stack unwinding even runs destructors before termination.

## Strong guarantee via copy-and-swap and commit phases

Writing `operator=` manually with raw resources easily violates even the basic guarantee:

```cpp
// Broken: if `new` throws, `data_` is left dangling!
RawBuffer& operator=(const RawBuffer& rhs) {
    delete[] data_;
    data_ = new std::byte[rhs.size_]; // throws std::bad_alloc -> UB on ~RawBuffer
    size_ = rhs.size_;
    return *this;
}
```

The idiomatic cure is **copy-and-swap**, which moves every fallible step (memory allocation and element copying) into the by-value parameter construction before executing a non-throwing swap:

```cpp
#include <algorithm>
#include <cstddef>
#include <memory>
#include <utility>

class PacketBuffer {
    std::unique_ptr<std::byte[]> data_;
    std::size_t size_ = 0;

public:
    PacketBuffer() = default;
    explicit PacketBuffer(std::size_t n)
        : data_(std::make_unique<std::byte[]>(n)), size_(n) {}

    PacketBuffer(const PacketBuffer& other)
        : data_(other.size_ ? std::make_unique<std::byte[]>(other.size_) : nullptr),
          size_(other.size_) {
        if (size_) std::copy_n(other.data_.get(), size_, data_.get());
    }

    PacketBuffer(PacketBuffer&&) noexcept = default;

    void swap(PacketBuffer& other) noexcept {
        using std::swap;
        swap(data_, other.data_);
        swap(size_, other.size_);
    }

    // Parameter construction may throw before entry; body is nothrow.
    PacketBuffer& operator=(PacketBuffer rhs) noexcept {
        swap(rhs);
        return *this;
    }
};
```

Here `rhs` acts as a temporary staging buffer. If copying throws `std::bad_alloc`, `*this` stays untouched—delivering both the strong guarantee and safe self-assignment (`buf = buf`) without extra branches.

When full copy-and-swap would duplicate megabytes across multiple containers, split work into **prepare** and **commit** phases: build new nodes or buffers in local state first, then commit via `noexcept` swaps or pointer transfers.

## Why noexcept controls vector reallocation

Marking a move constructor `noexcept` directly governs standard container performance. During `std::vector::push_back` reallocation, preserving the strong guarantee requires keeping old elements intact until all elements land in the new buffer. If `T`'s move constructor might throw, moving element #3 irreversibly alters the source buffer before element #5 throws.

Therefore `std::vector` relocates elements via `std::move_if_noexcept`, inspecting `std::is_nothrow_move_constructible_v<T>`:

```cpp
#include <string>
#include <type_traits>
#include <utility>

struct FragileMove {
    std::string label;
    FragileMove(FragileMove&& other) : label(std::move(other.label)) {} // NOT noexcept
    FragileMove(const FragileMove&) = default;
};

struct FastMove {
    std::string label;
    FastMove(FastMove&&) noexcept = default;
    FastMove(const FastMove&) = default;
};

static_assert(!std::is_nothrow_move_constructible_v<FragileMove>);
static_assert(std::is_nothrow_move_constructible_v<FastMove>);
```

> **Pitfall.** Defining a custom move constructor without `noexcept` silently forces `std::vector` to copy every element instead of moving on reallocation whenever a copy constructor exists—turning expected pointer swaps into expensive deep allocations.

For generic wrappers, write **conditional `noexcept`** expressions rather than guessing: `Wrapper(Wrapper&& other) noexcept(std::is_nothrow_move_constructible_v<T>)`. Meanwhile, move-only types (`std::unique_ptr`, or custom non-copyable handles) still get moved during `std::vector` growth because copying is unavailable, though leaving their move constructors non-`noexcept` downgrades `push_back` from the strong guarantee to the basic guarantee.

## Destructors, function-try-blocks, and uncaught_exceptions

Since C++11, every destructor is **implicitly `noexcept(true)`** unless a non-static member or base subobject has a potentially throwing destructor or the destructor explicitly declares `noexcept(false)` (`[class.dtor]`). Throwing an exception out of an implicitly `noexcept` destructor—whether during normal scope exit or during stack unwinding—immediately triggers `std::terminate()`.

Even if a destructor explicitly specifies `noexcept(false)`, letting an exception escape while another exception is already unwinding (`std::uncaught_exceptions() > 0`) still invokes `std::terminate()`. Destructors must therefore swallow, log, or assert on internal failures rather than emitting exceptions.

Two specialized language features interact closely with unwinding:

1. **Constructor function-try-blocks** wrap member initializers so you can log or translate exceptions thrown by bases or members. However, per `[except.handle]`, a `catch` block on a constructor or destructor cannot suppress the exception silently: reaching the closing brace without throwing a different exception or calling `return` (invalid in constructors) **implicitly rethrows** the active exception.

2. **`std::uncaught_exceptions()`** (plural, C++17) returns the count of active exceptions currently in flight on the calling thread—replacing the deprecated C++98 `bool std::uncaught_exception()`, which could not tell whether an exception was thrown *inside* a scope guard's lifetime when the guard itself was created during an outer stack unwind:

```cpp
#include <exception>
#include <utility>

template <class Fn>
class RollbackGuard {
    Fn rollback_;
    int entry_count_ = std::uncaught_exceptions();

public:
    explicit RollbackGuard(Fn fn) : rollback_(std::move(fn)) {}
    RollbackGuard(const RollbackGuard&) = delete;

    ~RollbackGuard() {
        if (std::uncaught_exceptions() > entry_count_) {
            rollback_();
        }
    }
};
```

Comparing the exit count against the entry snapshot lets transaction guards distinguish new failures from pre-existing outer unwinds cleanly.

> **Pitfall.** Placing a `try { ... } catch (...) {}` function-try-block on a constructor does not prevent the caller from receiving an exception; if execution reaches the end of the handler, C++ automatically rethrows.

## What to remember

- The **basic guarantee** (no leaks, valid invariants) is the non-negotiable minimum for all C++ types; achieve it effortlessly by owning resources through RAII handles.
- Achieve the **strong guarantee** by performing every potentially throwing allocation or copy on temporary state first, then committing via `noexcept` swaps or pointer transfers.
- Always mark user-declared move constructors and move assignment operators `noexcept` when they cannot throw, or `std::move_if_noexcept` will force containers like `std::vector` back into copying.
- Destructors are implicitly `noexcept(true)` since C++11; never let exceptions escape a destructor, and use `std::uncaught_exceptions()` (plural) to detect new unwinds inside scope guards.
- A constructor function-try-block can observe or translate a member-initializer exception, never swallow it.

## Concept Map Outline

- **Exception-Safety Guarantees:** Contracts governing object invariants, resource cleanup, and container behavior when C++ code throws.
  - **Abrahams Guarantee Levels:** Four graduated promises defining what state survives an exception.
    - **Nothrow and Nofail:** Operations guaranteed never to emit exceptions, forming the bedrock for commit phases.
    - **Strong Commit-Rollback:** Failed calls leave program state identical to before the call began.
    - **Basic No-Leak Invariants:** Mandatory baseline guaranteeing zero leaked resources and destructible, valid objects.
  - **Stack Unwinding Mechanics:** How runtime cleanup executes between throw and catch.
    - **Exception Object Storage:** Throw initializes an implementation-managed exception object outside unwinding frames.
    - **Partial Subobject Cleanup:** Completed bases and members destroy in reverse order while the outer destructor is skipped.
    - **std::terminate Triggers:** Uncaught exceptions or throws escaping noexcept functions abort without guaranteed unwinding.
  - **Strong Guarantee Patterns:** Idioms that isolate failure-prone work from state mutation.
    - **Copy-and-Swap Idiom:** By-value parameter construction isolates allocations before a nothrow swap mutates this.
    - **Prepare-Then-Commit Split:** Stage new allocations locally first, then publish with noexcept swaps and pointer moves.
  - **noexcept and Move Semantics:** Compile-time checks linking exception specs to container efficiency.
    - **std::move_if_noexcept:** Containers copy instead of moving unless the move constructor is noexcept or non-copyable.
    - **Conditional noexcept:** Propagate member noexcept traits using noexcept(expr) on generic wrappers.
    - **Implicitly noexcept Destructors:** Every destructor defaults to noexcept(true) unless a subobject or specifier opts out.
  - **Unwinding Edge Cases:** Language rules around constructor handlers and nested exceptions.
    - **Constructor Function-Try Blocks:** Handlers around member initializers can translate errors but implicitly rethrow on exit.
    - **std::uncaught_exceptions Depth:** Counting active exceptions lets scope guards detect new unwinds inside outer catches.

## Standardese Quiz Questions

### Question 1 [warmup] ([except], [res.on.exception.handling])

What does the basic exception-safety guarantee promise if a member function throws an exception?

A. All modified objects automatically roll back to their exact pre-call values
B. No resources are leaked and all class invariants remain intact, though values may have changed
C. The function is implicitly marked noexcept and calls std::terminate on error
D. Only stack-allocated primitives are rolled back while heap memory may leak

**Answer (B):** No resources are leaked and all class invariants remain intact, though values may have changed

**Why:** The basic guarantee requires zero resource leaks and preserved invariants so surviving objects remain valid and destructible, without promising value rollback (which is the strong guarantee).

### Question 2 [warmup] ([vector.modifiers], [utility.move.if.noexcept])

Why does std::vector::push_back copy elements instead of moving them during buffer reallocation when a copyable type's move constructor lacks noexcept?

```cpp
struct S {
    S(const S&);
    S(S&&); // not noexcept
};
```

A. The standard forbids calling non-noexcept move constructors anywhere in <vector>
B. Copy constructors are always faster than move constructors for small buffers
C. Moving irreversibly alters the source buffer, so throwing mid-reallocation would break push_back's strong guarantee
D. Non-noexcept move constructors make std::is_move_constructible_v<S> false

**Answer (C):** Moving irreversibly alters the source buffer, so throwing mid-reallocation would break push_back's strong guarantee

**Why:** std::vector uses std::move_if_noexcept to preserve its strong exception-safety guarantee on reallocation: if moving element i can throw, the old elements are already mutated, preventing rollback. When copy construction is available, vector falls back to copying.

### Question 3 [tricky] ([except.ctor], [basic.life])

In the snippet below, what happens if Foo's second member initializer (b(arg)) throws an exception?

```cpp
struct Foo {
    A a;
    B b;
    Foo(int arg) : a(), b(arg) {}
    ~Foo() { cleanup(); }
};
```

A. ~A() runs to destroy the completed subobject, and ~Foo() does not run
B. ~Foo() runs first, followed by ~A()
C. Neither ~A() nor ~Foo() runs because Foo never finished constructing
D. Both ~B() and ~A() run in reverse declaration order

**Answer (A):** ~A() runs to destroy the completed subobject, and ~Foo() does not run

**Why:** An object's lifetime begins only when its constructor completes. When b(arg) throws, b never began lifetime and Foo never finished construction, so ~Foo() and ~B() are skipped—only already-constructed subobjects (a) are destroyed in reverse order.

### Question 4 [tricky] ([uncaught.exceptions])

Why did C++17 introduce int std::uncaught_exceptions() to replace bool std::uncaught_exception()?

A. uncaught_exception() returned false inside noexcept functions
B. uncaught_exception() had a data race across threads
C. uncaught_exceptions() automatically suppresses secondary exceptions thrown in destructors
D. A boolean cannot distinguish a new inner exception from an outer unwind already active when a scope guard was constructed

**Answer (D):** A boolean cannot distinguish a new inner exception from an outer unwind already active when a scope guard was constructed

**Why:** If a RAII transaction guard is constructed inside a catch block or destructor during an outer unwind, uncaught_exception() is already true throughout its scope. Comparing exit count against entry count via std::uncaught_exceptions() accurately detects new unwinding.

### Question 5 [standardese] ([class.dtor], [except.spec])

In modern C++ (C++11 and later), what is the implicit exception specification of TrackedHolder::~TrackedHolder() below?

```cpp
struct Tracked {
    ~Tracked() noexcept(false) {}
};
struct TrackedHolder {
    Tracked t;
    ~TrackedHolder() = default;
};
```

A. noexcept(true), because all destructors are unconditionally noexcept
B. Potentially throwing (noexcept(false)), inherited from member subobject Tracked::~Tracked()
C. Ill-formed because a defaulted destructor cannot contain a throwing member
D. noexcept(true) unless TrackedHolder also holds a virtual base

**Answer (B):** Potentially throwing (noexcept(false)), inherited from member subobject Tracked::~Tracked()

**Why:** Per [class.dtor] and [except.spec], a destructor with no explicit noexcept specifier has the same exception specification as an implicitly declared one—which is noexcept(true) ONLY if all direct base and non-static member destructors are non-throwing. Tracked::~Tracked() is noexcept(false), making ~TrackedHolder() potentially throwing too.

### Question 6 [standardese] ([except.handle])

What happens when execution reaches the closing brace of the catch block in Wrapper's constructor function-try-block?

```cpp
struct Wrapper {
    Widget w;
    Wrapper(int x) try : w(x) {
    } catch (...) {
        log_error();
    }
};
```

A. Wrapper finishes constructing with w left uninitialized
B. The caught exception is swallowed and Wrapper throws std::bad_exception
C. The currently handled exception is implicitly rethrown
D. std::terminate() is called unconditionally

**Answer (C):** The currently handled exception is implicitly rethrown

**Why:** Under [except.handle], if control reaches the end of a handler of a function-try-block on a constructor or destructor without exiting via throw, the current exception is automatically rethrown—a constructor cannot recover and produce a half-constructed object.

# Optional, expected, and error codes

> Choosing value-based error channels in modern C++: std::optional, C++23 std::expected, monadic combinators, and std::error_code vs std::error_condition.

- **Source:** C++ Atlas (https://cppatlas.com/topics/optional-expected-and-error-codes)
- **Track:** Exceptions and error handling
- **Estimated reading time:** 10 minutes
- **ISO C++ clauses:** [optional] (https://eel.is/c++draft/optional), [expected] (https://eel.is/c++draft/expected), [syserr] (https://eel.is/c++draft/syserr), [syserr.errcode] (https://eel.is/c++draft/syserr.errcode), [syserr.errcondition] (https://eel.is/c++draft/syserr.errcondition), [syserr.errcat] (https://eel.is/c++draft/syserr.errcat)
- **cppreference links:** [std::optional](https://en.cppreference.com/w/cpp/utility/optional), [std::expected](https://en.cppreference.com/w/cpp/utility/expected), [std::unexpected](https://en.cppreference.com/w/cpp/utility/expected/unexpected), [std::error_code](https://en.cppreference.com/w/cpp/error/error_code), [std::error_condition](https://en.cppreference.com/w/cpp/error/error_condition), [std::system_error](https://en.cppreference.com/w/cpp/error/system_error)
- **Prerequisites:** exception-safety-guarantees, value-categories

Exceptions excel when errors cross many architectural layers toward a central recovery boundary, yet plenty of failures are local, expected outcomes: a missing cache entry, a malformed token, or a non-blocking socket returning `EAGAIN`. Modern C++ equips you with three composable value-returning abstractions—`std::optional`, C++23 `std::expected`, and `std::error_code`—that keep control flow explicit in function signatures with zero hidden heap allocation.

## Matching the channel to the failure

Selecting the right error vocabulary depends on whether callers need *why* something failed, whether failures are rare or routine, and whether status values cross OS or ABI boundaries.

| Mechanism | Meaning of non-value state | Carries error reason | Inline storage | Propagation style |
| --- | --- | --- | --- | --- |
| Exceptions | Stack unwind on exceptional path | Rich polymorphic type | Dynamic runtime object | Implicit across frames |
| `std::optional<T>` | Value absent is normal | None | `sizeof(T)` + flag | Explicit check or monadic |
| `std::expected<T, E>` | Operation failed with typed `E` | Typed payload `E` | Overlapping `T`/`E` + flag | Explicit check or monadic |
| `std::error_code` | OS or domain status code | Integer + category pointer | Two machine words | Return value or `system_error` |

Use `std::optional<T>` when absence carries no diagnostic ambiguity—finding a key in a map or parsing an optional header field. Reach for `std::expected<T, E>` when callers must inspect or propagate *why* a computation failed. Pair it with `std::error_code` when wrapping operating-system errors or unifying heterogeneous library error enums into a single compact type.

## std::optional and the monadic pipeline

`std::optional<T>` manages aligned inline storage alongside a boolean engagement state—never allocating on the heap. Reading a disengaged optional via `*opt` or `opt->member` triggers **undefined behavior**, whereas `opt.value()` performs a bounds check and throws `std::bad_optional_access`.

C++23 enriched `std::optional` with three monadic member functions that eliminate nested `if (!opt)` boilerplate:

- `.and_then(fn)` invokes `fn(*opt)` when engaged, where `fn` returns another `std::optional<U>`.
- `.transform(fn)` maps `*opt` through `fn` and wraps the result in `std::optional<U>` automatically.
- `.or_else(fn)` invokes `fn()` returning a fallback `std::optional<T>` only when disengaged.

```cpp
#include <optional>
#include <string_view>

std::optional<int> parse_port(std::string_view sv) {
    if (sv == "8080") return 8080;
    return std::nullopt;
}

int resolve_port(std::optional<std::string_view> raw) {
    return raw
        .and_then(parse_port)
        .transform([](int p) { return p + 1; })
        .value_or(80);
}
```

> **Pitfall.** Checking `if (opt)` on a `std::optional<bool>` tests whether a `bool` is present, **not** whether the contained `bool` is `true`. An engaged `std::optional<bool>{false}` is truthy in boolean contexts! Write `opt.value_or(false)` or `opt == true` to inspect the underlying boolean value.

Notice also that in C++23 `std::optional<T&>` is ill-formed; nullable non-owning references are expressed with raw pointers `T*` or `std::optional<std::reference_wrapper<T>>`.

## C++23 std::expected and std::unexpected

`std::expected<T, E>` models a discriminated union holding either an expected value `T` or an unexpected error `E`, stored inline without dynamic allocation. Unlike `std::optional`, it even supports `T = void` (`std::expected<void, E>`) for side-effectful functions whose only success payload is "no error occurred".

When `T` and `E` are identical or mutually convertible—for example `std::expected<int, int>`—constructing the error state requires wrapping the error in `std::unexpected(err)` (or using `std::unexpect` in-place tag):

```cpp
#include <expected>
#include <string_view>

enum class ParseErr { empty, invalid_digit };

std::expected<int, ParseErr> to_count(std::string_view sv) {
    if (sv.empty()) return std::unexpected(ParseErr::empty);
    if (sv[0] < '0' || sv[0] > '9') return std::unexpected(ParseErr::invalid_digit);
    return sv[0] - '0';
}

std::expected<int, int> disambiguate(bool fail) {
    if (fail) return std::unexpected(404); // constructs error E
    return 200;                            // constructs value T
}
```

`std::expected` mirrors the C++23 monadic API of `std::optional`, adding `.transform_error(fn)` so you can adapt a low-level error `E1` into a higher-level domain error `E2` mid-pipeline while preserving any `T` value untouched. Calling `.value()` on an unexpected state throws `std::bad_expected_access<E>`, whereas `.error()` on a value-holding expected is undefined behavior—always check `has_value()` or `if (res)` first.

> **Standardese.** Per `[expected.object.general]`, `std::expected<T, E>` guarantees that `T` and `E` occupy overlapping inline storage with no valueless-by-exception state whenever constructing the replacement alternative cannot throw or a nothrow-movable backup protects the switch.

## std::error_code vs std::error_condition

The `<system_error>` header contains two deceptively similar types whose distinction unlocks clean cross-platform APIs:

- **`std::error_code`** represents a **platform-specific or domain-specific raw error**: two machine words storing an integer code `int` plus a pointer `const std::error_category*`. It preserves exact OS details (such as POSIX `ENOENT` or Win32 `ERROR_FILE_NOT_FOUND`) for logging and diagnostics.
- **`std::error_condition`** represents a **portable semantic category** that application logic matches against—most commonly the POSIX-inspired `std::errc` enumerators such as `std::errc::no_such_file_or_directory` or `std::errc::permission_denied`.

> **Mental model.** Think of `std::error_code` as the raw sensor reading reported by a specific subsystem, and `std::error_condition` as the portable diagnosis your error-handling `if` statement checks against.

When you write `ec == std::errc::no_such_file_or_directory`, `<system_error>` invokes `ec.category().equivalent(...)` (calling `default_error_condition(ec.value())`) to translate a platform `error_code` into a portable `error_condition` without discarding the original OS code stored inside `ec`. Throwing `std::system_error(ec)` bridges the gap whenever a lower layer uses `error_code` and an upper layer expects exceptions.

## Custom error categories and zero-allocation design

You can plug your own error enum directly into `std::error_code` and `std::expected<T, std::error_code>` without modifying `<system_error>`. Three pieces complete the integration:

1. Define a `std::error_category` subclass returned from a singleton function (`error_category` equality compares object identity).
2. Specialize `std::is_error_code_enum<YourEnum>` as `std::true_type`.
3. Provide a free `make_error_code(YourEnum)` function in **your enum's own namespace** so argument-dependent lookup (ADL) discovers it automatically (never place overloads inside `namespace std`).

```cpp
#include <expected>
#include <string>
#include <system_error>
#include <type_traits>

enum class ConfigErr { missing_file = 1, bad_syntax = 2 };

class ConfigCategory final : public std::error_category {
public:
    const char* name() const noexcept override { return "config"; }
    std::string message(int ev) const override {
        switch (static_cast<ConfigErr>(ev)) {
            case ConfigErr::missing_file: return "configuration file not found";
            case ConfigErr::bad_syntax:   return "malformed configuration entry";
        }
        return "unknown config error";
    }
    std::error_condition default_error_condition(int ev) const noexcept override {
        if (static_cast<ConfigErr>(ev) == ConfigErr::missing_file) {
            return std::errc::no_such_file_or_directory;
        }
        return std::error_condition(ev, *this);
    }
};

inline const std::error_category& config_category() noexcept {
    static const ConfigCategory instance;
    return instance;
}

inline std::error_code make_error_code(ConfigErr e) noexcept {
    return {static_cast<int>(e), config_category()};
}

template <>
struct std::is_error_code_enum<ConfigErr> : std::true_type {};

std::expected<int, std::error_code> load_timeout(bool present) {
    if (!present) return std::unexpected(ConfigErr::missing_file);
    return 30;
}
```

Because `ConfigErr` opts into `std::is_error_code_enum`, callers can check `!res && res.error() == std::errc::no_such_file_or_directory` across any platform while keeping `res.error().message()` domain-specific and `sizeof(std::error_code)` fixed at two pointers.

> **Pitfall.** Unchecked dereferencing (`*opt`, `*res`) on an empty `std::optional` or error-holding `std::expected`—and calling `res.error()` on a value-holding `std::expected`—invokes undefined behavior rather than throwing. Guard access with `has_value()` or stick to `.value()`, `.value_or()`, and monadic combinators.

## What to remember

- Choose **`std::optional<T>`** when absence is normal and needs no explanation, **`std::expected<T, E>`** when callers must know *why* an operation failed, and **exceptions** when unwinding across decoupled layers.
- Never assume `if (opt)` checks the value inside `std::optional<bool>`; test `opt.value_or(false)` or compare against `true`.
- Prefer `.and_then`, `.transform`, `.or_else`, and `.transform_error` in C++23 to compose error pipelines without losing type safety or calling unchecked `*` / `.error()`.
- Store platform or domain failures in **`std::error_code`** and write portable comparisons against **`std::error_condition`** (`std::errc`).
- Define `make_error_code` in your custom enum's namespace for ADL alongside a `std::is_error_code_enum` specialization and a singleton `std::error_category`.

## Concept Map Outline

- **Optional, Expected, and Error Codes:** Value-based error channels representing absence, typed failures, and portable OS error diagnostics.
  - **Channel Selection Tradeoffs:** Matching failure frequency and diagnostic richness to the right C++ abstraction.
    - **Exceptions vs Return Values:** Exceptions decouple distant handlers while value returns keep local failure paths explicit.
    - **Zero-Allocation Inline Storage:** Optional, expected, and error_code store state inline without heap allocation.
  - **std::optional Patterns:** Nullable value wrapper for normal, self-explanatory absence.
    - **Checked vs Unchecked Access:** value() throws bad_optional_access on empty whereas operator* invokes undefined behavior.
    - **optional<bool> Truthiness Trap:** Contextual bool conversion tests engagement rather than the wrapped boolean value.
    - **C++23 Monadic Combinators:** and_then, transform, and or_else chain nullable computations without nested branches.
  - **C++23 std::expected:** Discriminated union holding either expected T or unexpected E.
    - **std::unexpected Disambiguation:** Explicitly marks error construction when T and E share or convert types.
    - **expected<void, E> Operations:** Represents side-effectful steps that succeed silently or return typed failure.
    - **Error Adaptation Pipelines:** transform_error translates low-level failures into domain errors along monadic chains.
  - **System Error Architecture:** Lightweight pairs distinguishing raw platform codes from portable meanings.
    - **std::error_code Values:** Holds a raw integer code and category pointer preserving exact OS diagnostics.
    - **std::error_condition Semantics:** Portable semantic target such as std::errc used inside cross-platform comparisons.
    - **std::system_error Bridge:** Exception wrapper carrying an error_code across exception-based boundaries.
  - **Custom Error Categories:** Extending <system_error> cleanly for user-defined domain enums.
    - **Singleton error_category:** Category identity relies on singleton address equality and default_error_condition mapping.
    - **is_error_code_enum and ADL:** Specializing the trait and defining make_error_code in your namespace enables implicit conversion.

## Standardese Quiz Questions

### Question 1 [warmup] ([expected.un.general], [expected.object.cons])

Why does std::expected<T, E> provide the wrapper type std::unexpected<E>?

A. Because E is always heap-allocated separately from T
B. To disambiguate error construction when T and E have the same or convertible types
C. Because E cannot be a scoped enum without wrapping
D. To automatically convert error return values into thrown exceptions

**Answer (B):** To disambiguate error construction when T and E have the same or convertible types

**Why:** If you return a plain value from a function returning std::expected<int, int> or std::expected<std::string, std::string_view>, overload resolution cannot tell whether an argument is a value or an error. std::unexpected(e) unambiguously selects the error alternative.

### Question 2 [warmup] ([syserr.errcode.overview], [syserr.errcondition.overview])

In <system_error>, what is the primary design difference between std::error_code and std::error_condition?

A. error_code represents platform/domain-specific raw codes, while error_condition represents portable semantic categories for matching
B. error_condition throws exceptions automatically whereas error_code does not
C. error_code allocates a std::string message while error_condition holds only an int
D. error_code is only for Windows APIs and error_condition is only for POSIX errno

**Answer (A):** error_code represents platform/domain-specific raw codes, while error_condition represents portable semantic categories for matching

**Why:** std::error_code preserves the exact platform or library error integer and category pointer, whereas std::error_condition (like std::errc) represents a portable abstraction you compare against via category equivalence.

### Question 3 [tricky] ([optional.observe])

What does the following C++23 code evaluate?

```cpp
std::optional<bool> flag = false;
if (flag) {
    // branch A
} else {
    // branch B
}
```

A. Branch B runs because the contained bool is false
B. Compilation fails because optional<bool> has an ambiguous operator bool
C. Branch A runs because explicit operator bool() checks engagement, not the wrapped bool
D. Undefined behavior because optional<bool> cannot hold false

**Answer (C):** Branch A runs because explicit operator bool() checks engagement, not the wrapped bool

**Why:** std::optional<T>::operator bool() always returns has_value(). Because flag holds the value false, it is engaged, so if (flag) enters Branch A. Use flag == true or flag.value_or(false) to test the contained value.

### Question 4 [tricky] ([expected.object.observe])

Given std::expected<int, std::string> r = 42;, what happens if you immediately call r.error() without checking r.has_value()?

```cpp
std::expected<int, std::string> r = 42;
auto& msg = r.error();
```

A. It returns an empty default-constructed std::string
B. It throws std::bad_expected_access<int>
C. Compilation fails unless wrapped in a try block
D. It triggers undefined behavior because r holds a value, not an error

**Answer (D):** It triggers undefined behavior because r holds a value, not an error

**Why:** Unlike r.value(), which throws std::bad_expected_access when holding an error, r.error() is an unchecked observer whose precondition is !has_value(). Calling r.error() on a value-holding expected is undefined behavior.

### Question 5 [standardese] ([syserr.errcode.constructors], [namespace.std])

When registering a custom enum class AppErr with std::error_code via std::is_error_code_enum<AppErr>, where must make_error_code(AppErr) be declared?

A. Inside namespace std alongside std::is_error_code_enum
B. Inside the same namespace as AppErr so ADL finds it
C. As a static member function of std::error_category
D. Only inside the translation unit defining main()

**Answer (B):** Inside the same namespace as AppErr so ADL finds it

**Why:** std::error_code's template constructor invokes unqualified make_error_code(e) so argument-dependent lookup (ADL) locates the overload in AppErr's associated namespace. Adding function overloads to namespace std is undefined behavior.

### Question 6 [standardese] ([expected.object.monadic])

In C++23, which call correctly transforms only the error channel of std::expected<int, ParseErr> e while passing any T value straight through?

A. e.or_else(map_err)
B. e.and_then(map_err)
C. e.transform_error(map_err)
D. e.transform(map_err)

**Answer (C):** e.transform_error(map_err)

**Why:** transform_error(f) applies f(*this->error()) when !has_value() and wraps the result in std::unexpected, returning a std::expected<T, NewErr>. If has_value() is true, transform_error forwards the existing T value unchanged.

---

# Track: Memory model

Storage duration, object lifetime, strict aliasing, multi-core atomics and smart-pointer control blocks.

# Object lifetime and storage

> Why raw memory allocation differs from object existence: storage durations, [basic.life] rules, implicit-lifetime types, std::launder, and temporary lifetime extension.

- **Source:** C++ Atlas (https://cppatlas.com/topics/object-lifetime-and-storage)
- **Track:** Memory model
- **Estimated reading time:** 11 minutes
- **ISO C++ clauses:** [basic.stc] (https://eel.is/c++draft/basic.stc), [basic.life] (https://eel.is/c++draft/basic.life), [intro.object] (https://eel.is/c++draft/intro.object), [ptr.launder] (https://eel.is/c++draft/ptr.launder), [class.temporary] (https://eel.is/c++draft/class.temporary), [stmt.ranged] (https://eel.is/c++draft/stmt.ranged)
- **cppreference links:** [Lifetime](https://en.cppreference.com/w/cpp/language/lifetime), [Storage class specifiers](https://en.cppreference.com/w/cpp/language/storage_duration), [Object](https://en.cppreference.com/w/cpp/language/object), [std::launder](https://en.cppreference.com/w/cpp/utility/launder), [std::start_lifetime_as](https://en.cppreference.com/w/cpp/memory/start_lifetime_as), [std::is_implicit_lifetime](https://en.cppreference.com/w/cpp/types/is_implicit_lifetime), [Range-based for loop](https://en.cppreference.com/w/cpp/language/range-for)
- **Prerequisites:** initialization-forms, value-categories, raii-and-resource-management

C++ separates **where and how long raw bytes exist** from **when a typed object legally lives inside those bytes**. Conflating the two leads to dangling pointers, broken placement-new code, and optimizer surprises when compilers reason about `const` members or uninitialized buffers.

## Storage duration versus object lifetime

Every region of memory backing an object has one of four **storage durations** (`[basic.stc]`):

| Storage duration | Obtained and released | Typical examples | Thread sharing |
| --- | --- | --- | --- |
| Static | Program startup until exit | Globals, `static` locals | Shared across all threads |
| Thread | Thread launch until thread exit | `thread_local` variables | Private per thread |
| Automatic | Block entry until block exit | Local variables, parameters | Stack-bound unless address shared |
| Dynamic | Explicit `new`/`malloc` until `delete`/`free` | Heap allocations, containers | Governed by ownership |

Storage duration governs only the raw memory. Under `[basic.life]`, an object's **lifetime** is a runtime property that starts only after storage with proper size and alignment is obtained **and** initialization completes (or vacuous initialization finishes for trivial types). Lifetime ends either when the destructor call **starts** (for class types with non-trivial destructors) or when the storage is reused or released.

> **Mental model.** Storage duration is a lease on an apartment; object lifetime is the tenancy itself. Holding keys to an empty apartment does not mean a tenant lives inside.

> **Standardese.** Per `[basic.life]/1`, for any class type with a non-trivial destructor, object lifetime ends the instant execution enters its destructor—before the destructor body even runs its first statement.

## Outside lifetime: what you can and cannot touch

Suppose you allocate raw aligned storage on the stack (`alignas(T) std::byte buf[sizeof(T)]`) or obtain memory from `operator new`. Before an object's lifetime begins—or after its destructor runs while the storage still remains allocated—a pointer `T*` pointing to that address has severe restrictions (`[basic.life]/6–7`):

- **Allowed:** converting the pointer to `void*`, passing it to placement `new` or `std::construct_at`, or comparing addresses (while storage still exists).
- **Undefined behavior:** reading or writing non-static data members, invoking non-static member functions, casting to a base class, or calling `delete` on the typed pointer.

C++20 added `std::construct_at(ptr, args...)` and `std::destroy_at(ptr)` in `<memory>` so custom containers and pools can start and end lifetimes cleanly—even inside `constexpr` evaluation, where raw placement `new` was historically disallowed until C++26.

## Implicit-lifetime types and start_lifetime_as

Before C++20, calling `std::malloc(sizeof(Packet))` and casting the returned `void*` to `Packet*` technically created undefined behavior because `malloc` allocates bytes without running constructors. Real C and systems code relied on it anyway.

C++20 solved this cleanly in `[intro.object]` by defining **implicit-lifetime types**: scalar types, aggregate classes with no user-provided constructors and trivial destructors (or eligible implicit-lifetime class types without user-provided destructors), and arrays of those types. Certain operations—`std::malloc`, `std::calloc`, `std::realloc`, `std::memcpy`, `std::memmove`, `operator new`, and creating a `std::byte` or `unsigned char` array—**implicitly create objects** of suitable implicit-lifetime types inside the region so the program's subsequent access has defined behavior.

C++23 went one step further with `std::start_lifetime_as<T>(ptr)` (and `std::start_lifetime_as_array<T>(ptr, n)`) for situations where raw bytes already hold a valid representation—such as memory-mapped files or socket buffers—and you want to read them in-place without copying:

```cpp
#include <cstddef>
#include <memory>
#include <type_traits>

struct PacketHeader {
    unsigned int seq;
    unsigned int length;
};
static_assert(std::is_implicit_lifetime_v<PacketHeader>);

unsigned int inspect_wire(const std::byte* aligned_bytes) {
    // Begins lifetime of PacketHeader in-place without copying or overwriting bytes.
    const auto* hdr = std::start_lifetime_as<PacketHeader>(aligned_bytes);
    return hdr->seq + hdr->length;
}
```

Ensure `aligned_bytes` already satisfies `alignof(PacketHeader)` and covers `sizeof(PacketHeader)` valid bytes; `std::start_lifetime_as` performs zero runtime instructions and zero-copy type blessing for the abstract machine.

## Reusing storage and why std::launder exists

When you destroy an object in place and placement-new a brand-new object into the **exact same address**, can older pointers `p` to the original object keep working?

Under `[basic.life]/8`, an existing pointer or reference is **transparently replaceable** only if every one of these holds:

1. The new object occupies the exact same storage location and has the **exact same type** (ignoring top-level cv-qualifiers).
2. The old object was a complete object (not a base-class subobject) or an array element whose replacement is also an array element.
3. The type contains **no `const` non-static data members** and **no reference non-static data members**.

If your struct contains a `const` field or reference member, an optimizer seeing `p->id` earlier may legally cache that constant forever—even across a placement `new (p)` call! You must either use the pointer returned by placement `new` directly or pass the stale pointer through `std::launder(p)` (`[ptr.launder]`):

```cpp
#include <memory>
#include <new>

struct Node {
    const int id;
    int payload;
};

int reuse_const_member() {
    Node* p = new Node{1, 10};
    p->~Node();

    Node* q = ::new (p) Node{2, 20};
    // p->id would be UB here because Node has a const member!
    int from_new = q->id;               // Well-defined: 2
    int from_launder = std::launder(p)->id; // Well-defined: 2

    std::destroy_at(q);
    ::operator delete(q);
    return from_new + from_launder;
}
```

> **Pitfall.** Placement-new reusing storage that holds a `const` or reference non-static member does **not** update pre-existing pointers to that address; dereferencing the old pointer without `std::launder` lets the compiler reuse stale cached values under `[basic.life]/8`.

Notice what `std::launder` does **not** do: it never creates an object or bypasses strict aliasing. It purely serves as an optimization barrier declaring that an already-live object of type `T` now resides at that address.

## Temporary materialization and the range-for fix

Temporaries materialized from prvalues normally survive only until the end of the **full-expression** containing them (typically the semicolon). Direct binding to a `const T&` or `T&&` reference extends the temporary's lifetime to match the reference's scope (`[class.temporary]`).

That rule has a notorious boundary: **lifetime extension never propagates through function calls or chained member accesses** (except direct subobject selection on the temporary itself, like `const int& m = make_pair().first;`). Calling `const char* s = make_name().c_str();` or capturing a `std::string_view` over a temporary `std::string` creates an instant dangling pointer at the semicolon.

For twelve years, range-based `for` loops suffered from the exact same cliff because their desugaring bound `auto&& __range = range_expr;`. Writing `for (int v : make_holder().items)` extended only `.items` while destroying the outer `Holder` temporary before iteration began! C++23 paper P2718R0 finally fixed `[stmt.ranged]`:

```cpp
#include <vector>

struct Holder {
    std::vector<int> items{1, 2, 3};
};
Holder make_holder() { return {}; }

int sum_items() {
    int total = 0;
    // Pre-C++23: UB (Holder temporary died before loop body).
    // C++23 (P2718R0): Well-defined; all temporaries in initializer extend across loop.
    for (int v : make_holder().items) {
        total += v;
    }
    return total;
}
```

> **Pitfall.** Even in C++23, temporary lifetime extension protects only direct reference binding and range-for initializers—returning a view (`std::string_view`, `std::span`) or calling `.c_str()` on a temporary still dangles the moment the full-expression ends.

## What to remember

- **Storage duration** controls raw memory allocation; **object lifetime** starts only after initialization completes and ends when destruction begins or storage is reused.
- Never read members or call member functions on uninitialized or already-destroyed storage; use `std::construct_at` and `std::destroy_at` to manage raw buffers cleanly.
- Use C++20 **implicit-lifetime types** and C++23 **`std::start_lifetime_as`** instead of pointer punning when interpreting raw byte buffers in place.
- Capture placement `new`'s return pointer or apply **`std::launder`** whenever replacing an object whose class has `const` or reference members.
- Remember that C++23 extended temporary lifetimes inside **range-for initializers** (`P2718R0`), while view types and accessors on temporaries outside range-for still dangle at the semicolon.

## Concept Map Outline

- **Object Lifetime and Storage:** Distinguishing when raw memory exists from when a C++ object legally lives inside it.
  - **Four Storage Durations:** Rules governing allocation and release of raw memory backing objects.
    - **Static and Thread:** Program-wide shared globals and per-thread thread_local storage lifetimes.
    - **Automatic and Dynamic:** Scope-bound stack storage versus explicit heap allocations via new or malloc.
  - **Lifetime Lifecycle Rules:** Exact boundaries when an object starts and stops existing.
    - **Start Upon Initialization:** Lifetime begins only once aligned storage is obtained and initialization completes.
    - **End When Destructor Starts:** Non-trivial objects lose lifetime the moment their destructor starts executing.
    - **construct_at and destroy_at:** C++20 utilities starting and ending lifetimes explicitly even inside constexpr.
  - **Implicit-Lifetime Types:** C++20 and C++23 rules blessing raw byte buffers without constructors.
    - **Implicit Object Creation:** malloc, memcpy, and byte arrays implicitly create scalars and eligible aggregates.
    - **std::start_lifetime_as:** C++23 zero-copy helper beginning object lifetime over existing wire bytes.
  - **Storage Reuse and Launder:** Pointer validity rules when placement new replaces an existing object.
    - **Transparent Replaceability:** Old pointers stay valid only for exact same types lacking const or reference members.
    - **std::launder Barrier:** Prevents optimizers from caching stale const or reference values across placement new.
  - **Temporary Lifetime Extension:** When materialized prvalues outlive their enclosing full-expression.
    - **Direct Reference Binding:** Binding const T& or T&& directly extends a temporary to the reference scope.
    - **Accessor Dangling Cliff:** Calling .c_str() or returning views stops extension at the semicolon.
    - **C++23 Range-For Fix:** P2718R0 extends all temporaries inside the range-for initializer across the loop.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.life])

When does the lifetime of an object with a non-trivial destructor end according to [basic.life]?

A. Only after free() or operator delete returns the storage to the OS
B. Once all pointers to the object go out of scope
C. The moment the destructor call starts, before its body finishes
D. When the last statement inside the destructor body finishes executing

**Answer (C):** The moment the destructor call starts, before its body finishes

**Why:** Under [basic.life]/1, for an object of a class type with a non-trivial destructor, lifetime ends when the destructor call starts (or when storage is reused/released without running the destructor).

### Question 2 [warmup] ([obj.lifetime], [intro.object])

Which C++23 standard library function starts the lifetime of an implicit-lifetime type T in existing raw bytes without copying or overwriting their contents?

A. std::start_lifetime_as<T>
B. std::launder<T>
C. std::construct_at<T>
D. std::assume_aligned<T>

**Answer (A):** std::start_lifetime_as<T>

**Why:** C++23 std::start_lifetime_as<T>(ptr) implicitly creates an object of implicit-lifetime type T whose value corresponds to the existing byte representation at ptr, avoiding a redundant std::memcpy.

### Question 3 [tricky] ([stmt.ranged], [class.temporary])

In C++17 and C++20 (before C++23 P2718R0), what happens in this range-based for loop?

```cpp
struct Holder { std::vector<int> items{1, 2, 3}; };
Holder make_holder();
for (int x : make_holder().items) {
    use(x);
}
```

A. Well-defined because range-for always extends the entire initializer expression
B. Ill-formed because make_holder() returns a prvalue
C. Well-defined only if int x is replaced with auto&& x
D. Undefined behavior because the Holder temporary is destroyed before the loop body begins

**Answer (D):** Undefined behavior because the Holder temporary is destroyed before the loop body begins

**Why:** Before C++23, range-for desugared to auto&& __range = make_holder().items;. Because __range bound to the member reference returned/accessed rather than extending Holder across the whole expression, Holder died at the semicolon before iteration started. C++23 P2718R0 fixed this specifically for range-for.

### Question 4 [tricky] ([class.temporary])

Why does std::string_view sv = std::string("hello") + " world"; produce a dangling view despite const reference extension rules?

```cpp
std::string_view sv = std::string("hello") + " world";
```

A. std::string_view allocates on the heap and leaks
B. Temporary lifetime extension applies to direct reference bindings, not user-defined class values like std::string_view
C. std::string literals are destroyed at block entry
D. String concatenation yields an lvalue rather than a prvalue

**Answer (B):** Temporary lifetime extension applies to direct reference bindings, not user-defined class values like std::string_view

**Why:** Lifetime extension under [class.temporary] extends a temporary ONLY when bound directly to a reference (const T& or T&&). std::string_view is a class type holding a pointer and length; the temporary std::string dies at the semicolon, leaving sv dangling.

### Question 5 [standardese] ([basic.life], [ptr.launder])

After destroying a Node with a const int member and constructing a new Node in the same storage via ::new (p) Node{2}, why is reading p->id directly undefined behavior?

```cpp
struct Node { const int id; };
Node* p = new Node{1};
p->~Node();
::new (p) Node{2};
```

A. Because Node has a const non-static data member, old pointer p is not transparently replaceable under [basic.life]/8
B. Because placement new changes the virtual address of p
C. Because const int members cannot be destroyed explicitly
D. Because Node lacks a user-declared move constructor

**Answer (A):** Because Node has a const non-static data member, old pointer p is not transparently replaceable under [basic.life]/8

**Why:** Under [basic.life]/8, an old pointer automatically refers to a newly created object at the same storage ONLY if the class has no const or reference non-static data members (among other rules). You must use the pointer returned by placement new or std::launder(p).

### Question 6 [standardese] ([ptr.launder])

Which of the following is true of std::launder(p) when p points to raw bytes where no object of type T has ever been constructed?

A. std::launder(p) implicitly begins the lifetime of a T at p
B. std::launder(p) disables strict aliasing rules for T
C. Calling std::launder(p) violates its precondition because no live object of type T exists at that address
D. std::launder(p) converts any void* into a valid T* safely

**Answer (C):** Calling std::launder(p) violates its precondition because no live object of type T exists at that address

**Why:** Per [ptr.launder], std::launder(p) requires that an object of type T is ALREADY within its lifetime at the address represented by p. It never creates an object (use placement new, std::construct_at, or std::start_lifetime_as for that).

# Object layout and alignment

> What the standard actually promises about sizeof, alignof, member order and padding, which class properties unlock byte-level tricks, and where the standard stops and the ABI takes over.

- **Source:** C++ Atlas (https://cppatlas.com/topics/object-layout-and-alignment)
- **Track:** Memory model
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [basic.align] (https://eel.is/c++draft/basic.align), [basic.types.general] (https://eel.is/c++draft/basic.types.general), [intro.object] (https://eel.is/c++draft/intro.object), [intro.memory] (https://eel.is/c++draft/intro.memory), [class.mem] (https://eel.is/c++draft/class.mem), [class.prop] (https://eel.is/c++draft/class.prop), [class.bit] (https://eel.is/c++draft/class.bit), [dcl.attr.nouniqueaddr] (https://eel.is/c++draft/dcl.attr.nouniqueaddr), [expr.sizeof] (https://eel.is/c++draft/expr.sizeof), [support.types.layout] (https://eel.is/c++draft/support.types.layout)
- **cppreference links:** [Object (size, alignment, representation)](https://en.cppreference.com/w/cpp/language/object), [alignas specifier](https://en.cppreference.com/w/cpp/language/alignas), [Empty base optimization](https://en.cppreference.com/w/cpp/language/ebo), [C++ attribute: no_unique_address](https://en.cppreference.com/w/cpp/language/attributes/no_unique_address), [Bit-field](https://en.cppreference.com/w/cpp/language/bit_field), [std::has_unique_object_representations](https://en.cppreference.com/w/cpp/types/has_unique_object_representations), [offsetof](https://en.cppreference.com/w/cpp/types/offsetof)
- **Prerequisites:** object-lifetime-and-storage

## The one idea

The standard describes layout as a set of relationships, not a set of numbers. It promises that members appear in declaration order, that every object is suitably aligned, that `sizeof` counts padding, and that certain classes can be treated as raw bytes. The actual offsets, padding amounts and vtable shapes come from the platform ABI, such as the Itanium C++ ABI used by GCC and Clang on Linux and macOS, or the MSVC ABI on Windows.

> **Mental model.** Ask two separate questions about any layout claim. First, does the standard guarantee it, so it holds on every conforming implementation? Second, does my ABI guarantee it, so it holds for this compiler, target and flag set? Most layout bugs come from answering the second question and believing you answered the first.

## Size, alignment and padding

Every complete object type has a size, given by `sizeof`, and an alignment, given by `alignof`. The alignment is a power of two, and an object of that type may only live at an address that is a multiple of it. Arrays have no gaps between elements, and the size of an array of `n` elements is exactly `n` times the element size. Because every element must be aligned, `sizeof(T)` is always a multiple of `alignof(T)`. That is why padding appears at the end of a struct as well as in the middle.

The character types have size 1 by definition. The sizes of `bool`, `int`, pointers and every other fundamental type are implementation-defined. A byte is at least eight bits, and `CHAR_BIT` tells you how many.

Within a class, members are placed at increasing addresses in declaration order. Until C++20 that rule only applied among members with the same access control; C++23 adopted P1847, so the order now holds regardless of `public` and `private` sections. Between members, the implementation inserts whatever padding the alignment of the next member needs. The standard does not reorder members for you, so declaration order matters.

```cpp
struct A { char c; double d; char e; };   // c, 7 padding bytes, d, e, 7 tail padding bytes
struct B { double d; char c; char e; };   // d, c, e, 6 tail padding bytes

// Holds on x86-64 System V and AArch64 (Linux and Apple): double is 8-aligned
static_assert(sizeof(A) == 24 && sizeof(B) == 16);
```

On those ABIs the two structs look like this, one character per byte, with dots for padding.

```text
A: c . . . . . . . d d d d d d d d e . . . . . . .   24 bytes
B: d d d d d d d d c e . . . . . .                   16 bytes
```

### Over-aligned types

`alignas` raises the alignment of a type or variable. It cannot lower it below the natural alignment. Any alignment greater than `alignof(std::max_align_t)` is called extended, and support for each extended alignment is implementation-defined. Before C++17, `new` ignored extended alignment and could hand you a misaligned object. P0035, adopted in C++17, added the `operator new` overloads that take `std::align_val_t`. A new-expression now calls them automatically for any type whose alignment exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`.

```cpp
#include <cstdint>
struct alignas(64) CacheLine { char bytes[64]; };

int main() {
  auto* p = new CacheLine;   // C++17: calls operator new(size_t, align_val_t{64})
  bool ok = reinterpret_cast<std::uintptr_t>(p) % 64 == 0;   // guaranteed true
  delete p;                  // calls the matching aligned operator delete
  return ok ? 0 : 1;
}
```

The value of `alignof(std::max_align_t)` is a reminder of how platform-specific this is. Homebrew GCC 16 and Clang 21 on the same Apple arm64 machine report 16 and 8 respectively.

## The class-property vocabulary

Several class properties decide what you may do with an object's bytes. They are easy to mix up.

A **trivially copyable** class has at least one eligible copy or move operation, every eligible one is trivial, and its destructor is trivial and not deleted. That is the property that lets you copy an object with `memcpy` and get an equal object, and it is what `std::bit_cast` requires. Deleted operations are not eligible, so a class with a reference member is still trivially copyable, even though its copy assignment is deleted.

A **standard-layout** class has no virtual functions or virtual bases, uses the same access control for all non-static data members, declares all of those members in one class of its hierarchy, and meets a few rules about base classes. That property makes `offsetof` well-defined and makes the object pointer-interconvertible with its first member. It also makes the common-initial-sequence rule for unions apply, and it is the C-compatibility property.

**POD**, meaning trivial and standard-layout, is a legacy name. `std::is_pod` was deprecated in C++20 because no rule in the language needs the combination.

```cpp
#include <type_traits>
struct Ref { int& r; };                        // copy assignment is implicitly deleted
struct Dtor { int x; ~Dtor() {} };             // user-provided destructor
struct Mixed { public: int a; private: int b; };
static_assert(std::is_trivially_copyable_v<Ref>);    // deleted means not eligible
static_assert(!std::is_trivially_copyable_v<Dtor>);
static_assert(!std::is_standard_layout_v<Mixed>);    // mixed access control
```

> **Pitfall.** Trivially copyable does not mean "has no padding", and it does not mean "safe to compare with `memcmp`". Those are questions about the object representation, covered at the end of this page.

## Empty classes, the empty base optimization and no_unique_address

An empty class still has a size of at least 1 as a complete object, because two distinct objects of the same type must have distinct addresses. A base class subobject, however, may occupy zero bytes. That is the empty base optimization, and it is why policy classes and empty allocators are traditionally inherited from rather than stored as members.

C++20 added `[[no_unique_address]]`, which lets a non-static data member share its address with other members. The member becomes a potentially-overlapping subobject, like a base class. The attribute permits overlap but does not require it. The distinct-address rule still applies, so two empty members of the same type cannot both sit at the same offset.

```cpp
struct Empty {};
struct One { [[no_unique_address]] Empty e; int x; };
struct Two { [[no_unique_address]] Empty a; [[no_unique_address]] Empty b; int x; };

// Itanium ABI (GCC, Clang on Linux and macOS):
static_assert(sizeof(One) == 4);   // e overlaps x at offset 0
static_assert(sizeof(Two) == 4);   // a at 0, b at 1, both overlapping x
```

The MSVC ABI is different. MSVC accepts `[[no_unique_address]]` but ignores it, for ABI compatibility. Code that needs the effect there uses `[[msvc::no_unique_address]]`, so portable libraries usually hide the choice behind a macro.

## Bit-fields

A bit-field is a member with an explicit width in bits. Almost everything about how bit-fields are allocated is implementation-defined. That covers the size of the allocation unit, whether a field may straddle two units, and whether fields are filled from the low end or the high end. You cannot take a bit-field's address or apply `sizeof` to it, and a non-const reference cannot bind to one.

One bit-field rule is fully standard and matters a great deal for threads. A maximal run of adjacent bit-fields of nonzero width forms a single memory location. Two threads writing two different bit-fields in the same run, without synchronization, therefore have a data race. A zero-width unnamed bit-field, written `int : 0;`, ends the run and starts a new memory location.

```cpp
struct Flags {
  unsigned ready : 1;   // ready and dirty share one memory location
  unsigned dirty : 1;
  unsigned : 0;         // forces the next bit-field into a new allocation unit
  unsigned owner : 4;   // separate memory location: safe to write concurrently with ready
};
```

## Bases and vtables: ABI, not standard

The standard says almost nothing about how base classes, virtual functions and virtual bases are laid out. It does not mention a vtable at all. It only requires that polymorphic classes are not standard-layout, which is why `offsetof` on them is conditionally-supported since C++17 rather than well-defined.

The following describes the Itanium C++ ABI, which GCC and Clang use on Linux and macOS for both x86-64 and AArch64. A dynamic class stores a vtable pointer at offset 0. Its primary base shares that pointer and also sits at offset 0. Other non-virtual bases follow in declaration order, then the class's own members. Virtual bases are placed at the end of the most-derived object, and their offsets are stored in the vtable so that code can find them at run time. The MSVC ABI makes different choices, including a separate virtual-base-table pointer. None of this is portable knowledge, but all of it is stable within an ABI, which is what lets separately compiled libraries interoperate.

## Object representation and value representation

The object representation of a `T` is the sequence of `sizeof(T)` `unsigned char` objects it occupies. The value representation is the set of bits that determine its value. The bits in between are padding bits, and their contents are not part of the value. Assigning or aggregate-initializing a struct does not promise anything about its padding. Zero-initialization does set the padding bits to zero. It happens to every object with static storage duration, and value-initialization such as `T()` performs it for a class without a user-provided or deleted default constructor. Note that `T{}` on an aggregate is aggregate initialization, which makes no such promise about padding.

```text
struct P { char c; int i; };   // common ABIs: sizeof(P) == 8
offset: 0   1   2   3   4   5   6   7
        c   pad pad pad i   i   i   i
```

Two `P` objects with equal members can therefore differ in bytes 1 to 3, so `memcmp` and byte-wise hashing are unreliable for them. The C++17 trait `std::has_unique_object_representations_v<T>` is true only when equal values are guaranteed to have identical bytes. It is false for `P` on common ABIs because of the padding. It is also typically false for floating-point types, where `+0.0` and `-0.0` compare equal with different bits. Use it as a `static_assert` guard before hashing or comparing raw bytes.

> **Standardese.** [basic.types.general] promises that for a trivially copyable `T`, outside of potentially-overlapping subobjects, copying an object's underlying bytes into another `T` object makes it hold the same value. It promises nothing about comparing those bytes, because padding bits are outside the value representation.

## What to remember

- The standard gives relationships and the ABI gives numbers. Only state a concrete `sizeof` together with the ABI it comes from.
- `sizeof(T)` is a multiple of `alignof(T)`, character types have size 1, and every other fundamental size is implementation-defined.
- Members are allocated in declaration order, regardless of access control since C++23 (P1847). Sort members by decreasing alignment to cut padding.
- Since C++17, `new` honors extended alignment through the `std::align_val_t` overloads.
- Trivially copyable means `memcpy` and `std::bit_cast` work. Standard-layout means `offsetof` and C compatibility. POD is a deprecated name for both together.
- Empty bases may take zero bytes. `[[no_unique_address]]` (C++20) does the same for members, except under MSVC, which needs `[[msvc::no_unique_address]]`.
- Bit-field allocation is implementation-defined, but adjacent nonzero-width bit-fields are one memory location, which matters for data races.
- Vtables and base placement are Itanium or MSVC ABI facts, not standard facts.
- Padding bits are not part of the value, so check `std::has_unique_object_representations_v` before hashing or comparing bytes.

## Concept Map Outline

- **Object layout and alignment:** The standard guarantees relationships; the ABI supplies the actual numbers.
  - **Size and alignment:** Every complete type has a size and a power-of-two alignment.
    - **sizeof multiple of alignof:** Arrays have no gaps and every element is aligned, so size is a multiple of alignment.
    - **Fundamental sizes:** Character types are size 1; bool, int, pointers and the rest are implementation-defined.
    - **Over-alignment:** alignas raises alignment; since C++17 new uses align_val_t overloads for extended alignment.
  - **Member order and padding:** Members sit at increasing addresses in declaration order, with padding for alignment.
    - **C++23 order rule:** P1847: declaration order holds regardless of access control; before C++23 only within one access level.
    - **Sort by alignment:** The compiler never reorders members, so sorting by decreasing alignment shrinks padding.
  - **Class properties:** Properties that decide what you may do with an object's bytes.
    - **Trivially copyable:** Eligible copy/move ops all trivial plus trivial destructor; enables memcpy and bit_cast.
    - **Standard-layout:** No virtuals, uniform member access, members in one class; enables offsetof and C compatibility.
    - **POD is deprecated:** Trivial plus standard-layout; std::is_pod was deprecated in C++20.
  - **Empty subobjects:** Complete empty objects have nonzero size, but subobjects may overlap others.
    - **Empty base optimization:** An empty base subobject may occupy zero bytes.
    - **[[no_unique_address]]:** C++20: members may overlap like bases; MSVC ignores it and needs [[msvc::no_unique_address]].
    - **Distinct address rule:** Two objects of the same type never share an address, so same-type empties cannot overlap each other.
  - **Bit-fields and ABI:** The parts of layout the standard leaves to the implementation.
    - **Bit-field allocation:** Unit size, straddling and bit order are implementation-defined; no address or sizeof.
    - **One memory location:** Adjacent nonzero-width bit-fields form one memory location; a :0 field starts a new one.
    - **Vtables are ABI:** Itanium puts the vptr at offset 0 and virtual bases last; the standard never mentions vtables.
    - **offsetof limits:** Use on non-standard-layout types is conditionally-supported since C++17.
  - **Representations:** Object representation is all sizeof(T) bytes; value representation is the bits that matter.
    - **Padding bits:** Not part of the value; member-wise init leaves them unspecified, zero-initialization clears them.
    - **Unique representations:** has_unique_object_representations (C++17) is false with padding and typically for floats.

## Standardese Quiz Questions

### Question 1 [warmup] ([class.mem], [basic.align], [expr.sizeof])

On x86-64 Linux (System V ABI, GCC or Clang), what are `sizeof(A)` and `sizeof(B)`?

```cpp
struct A { char c; double d; char e; };
struct B { double d; char c; char e; };
```

A. 10 and 10
B. 16 and 16
C. 24 and 16
D. 24 and 24

**Answer (C):** 24 and 16

**Why:** `double` is 8-byte aligned on this ABI. In `A`, `c` is followed by 7 padding bytes so that `d` lands at offset 8, and `e` at offset 16 needs 7 tail-padding bytes so that the size is a multiple of 8: 24 in total. In `B`, `d` comes first, then `c` and `e` at offsets 8 and 9, and the size rounds up to 16. The compiler may not reorder members to save space, because members are allocated in declaration order, so the answer 16 and 16 is wrong.

### Question 2 [warmup] ([expr.sizeof], [basic.align], [dcl.array])

Which statement does the C++ standard guarantee for every complete object type `T`?

A. `sizeof(bool) == 1`
B. `alignof(T) <= alignof(std::max_align_t)`
C. For a standard-layout `T`, `sizeof(T)` equals the sum of the sizes of its members
D. `sizeof(T)` is a multiple of `alignof(T)`

**Answer (D):** `sizeof(T)` is a multiple of `alignof(T)`

**Why:** Arrays have no gaps, and an array of `n` elements has size `n * sizeof(T)`, yet every element must be suitably aligned. Together these force `sizeof(T)` to be a multiple of `alignof(T)`. `sizeof(bool)` is implementation-defined even though it is 1 on every mainstream ABI. `alignas` can create over-aligned types beyond `max_align_t`, and standard-layout types can still contain padding.

### Question 3 [warmup] ([dcl.attr.nouniqueaddr], [intro.object])

With GCC or Clang on x86-64 Linux (Itanium C++ ABI), what is `sizeof(S)`?

```cpp
struct Empty {};
struct S {
  [[no_unique_address]] Empty e;
  int x;
};
```

A. 4
B. 8
C. 5
D. 1

**Answer (A):** 4

**Why:** `[[no_unique_address]]` (C++20) makes `e` a potentially-overlapping subobject, and the Itanium ABI places it at offset 0, overlapping `x`, so `S` is the size of one `int`. Without the attribute, `e` would take at least one byte, and `x`'s alignment would make the struct 8. The attribute only permits overlap: MSVC ignores it and needs `[[msvc::no_unique_address]]`, which is why the prompt pins the ABI.

### Question 4 [tricky] ([intro.object], [dcl.attr.nouniqueaddr])

With GCC or Clang on x86-64 Linux (Itanium C++ ABI), what is `sizeof(T)`?

```cpp
struct Empty {};
struct T {
  [[no_unique_address]] Empty a;
  [[no_unique_address]] Empty b;
  int x;
};
```

A. 8, because `a` and `b` cannot overlap so they need their own storage before `x`
B. 4, with `a` and `b` at the same offset
C. 4, with `a` at offset 0 and `b` at offset 1, both overlapping `x`
D. Ill-formed: two `[[no_unique_address]]` members of the same type

**Answer (C):** 4, with `a` at offset 0 and `b` at offset 1, both overlapping `x`

**Why:** Two distinct objects of the same type must have distinct addresses, so `a` and `b` cannot share an offset. Nothing stops either from overlapping `x`, though. The Itanium ABI puts `a` at 0 and `b` at 1, both inside `x`'s bytes, and the size stays 4. GCC 16 and Clang 21 both report offsets 0, 1 and 0. The tempting answer 'same offset' breaks the distinct-address rule, and 8 assumes overlap with a non-empty member is forbidden.

### Question 5 [tricky] ([basic.types.general], [dcl.init.general], [meta.unary.prop])

Assume an ABI where `P` has 3 padding bytes after `c`. What can you say about `same`?

```cpp
#include <cstring>
struct P { char c; int i; };

bool same() {
  P a{'x', 1};
  P b{'x', 1};
  return std::memcmp(&a, &b, sizeof(P)) == 0;
}
```

A. It is always `true`, because the members are equal and `P` is trivially copyable
B. It is not guaranteed to be `true`: brace-initializing the members says nothing about the padding bytes
C. It is always `false`, because padding bytes are poisoned
D. Ill-formed: `memcmp` requires a type with unique object representations

**Answer (B):** It is not guaranteed to be `true`: brace-initializing the members says nothing about the padding bytes

**Why:** The padding bytes are not part of the value representation, and aggregate initialization of the members does not set them, so two equal `P` objects may differ in bytes 1 to 3. Trivially copyable only guarantees that copying the bytes reproduces the value, not that equal values have equal bytes. `std::has_unique_object_representations_v<P>` is `false` on such an ABI, and checking it is how you guard byte-wise comparison or hashing. Zero-initialization, for example of a static `P` or of `P()`, would zero the padding.

### Question 6 [tricky] ([support.types.layout], [class.prop])

What is the status of `offsetof(V, x)` in C++23?

```cpp
#include <cstddef>
struct V {
  virtual ~V() = default;
  int x;
};
std::size_t off = offsetof(V, x);
```

A. Ill-formed: `offsetof` requires a standard-layout type
B. Undefined behavior
C. Conditionally-supported, because `V` is not standard-layout
D. Well-defined and equal to `sizeof(void*)`

**Answer (C):** Conditionally-supported, because `V` is not standard-layout

**Why:** Since C++17, using `offsetof` with a type that is not standard-layout is conditionally-supported. An implementation may accept it with its own meaning, or reject it with a diagnostic. Before C++17 it was undefined behavior, which is where the tempting UB answer comes from. GCC and Clang accept it with a `-Winvalid-offsetof` warning and give 8 on 64-bit Itanium targets, because the vtable pointer sits at offset 0, but that number is an ABI fact.

### Question 7 [standardese] ([class.mem], [expr.rel])

In C++23, given an object `s` of type `S`, is `&s.a < &s.b && &s.b < &s.c` (comparing as `void*` inside a member function) guaranteed to be true?

```cpp
struct S {
public:
  int a;
private:
  int b;
public:
  int c;
};
```

A. Yes: since C++23, non-zero-size members are allocated in declaration order regardless of access
B. No: only `a` before `c` is guaranteed, because `b` has different access control
C. Unspecified: member order is entirely up to the implementation
D. Implementation-defined, and it must be documented

**Answer (A):** Yes: since C++23, non-zero-size members are allocated in declaration order regardless of access

**Why:** C++23 adopted P1847, which removed the access-control exception: non-static data members of non-zero size of a non-union class are now allocated so that later members have higher addresses. Before C++23, the guarantee only covered members with the same access control, so the first option describes C++20. In practice no major compiler ever reordered members across access specifiers, which is why the change was uncontroversial.

### Question 8 [standardese] ([class.prop], [special], [class.copy.ctor])

Which of these class types is **not** trivially copyable?

A. `struct R { int& r; };`
B. `struct D { int x; ~D() {} };`
C. `struct E { E(); int x; };`
D. `struct A { int x; A(const A&) = default; A& operator=(const A&) = delete; };`

**Answer (B):** `struct D { int x; ~D() {} };`

**Why:** A trivially copyable class needs at least one eligible copy or move operation, every eligible one trivial, and a trivial, non-deleted destructor. `D`'s user-provided destructor is non-trivial, so it fails. `R` and `A` are tempting because their copy assignment is deleted, but deleted functions are not eligible, and each still has a trivial copy constructor. `E`'s user-provided default constructor is not a copy or move operation, so it does not matter.

# Strict aliasing and undefined behavior

> Why the optimizer relies on type-based alias analysis, what [basic.lval] permits, why union punning fails in C++, and how std::bit_cast replaces pointer casts.

- **Source:** C++ Atlas (https://cppatlas.com/topics/strict-aliasing-and-ub)
- **Track:** Memory model
- **Estimated reading time:** 10 minutes
- **ISO C++ clauses:** [basic.lval] (https://eel.is/c++draft/basic.lval), [intro.abstract] (https://eel.is/c++draft/intro.abstract), [expr.reinterpret.cast] (https://eel.is/c++draft/expr.reinterpret.cast), [bit.cast] (https://eel.is/c++draft/bit.cast), [class.union] (https://eel.is/c++draft/class.union), [class.mem.general] (https://eel.is/c++draft/class.mem.general)
- **cppreference links:** [Undefined behavior](https://en.cppreference.com/w/cpp/language/ub), [The as-if rule](https://en.cppreference.com/w/cpp/language/as_if), [reinterpret_cast conversion](https://en.cppreference.com/w/cpp/language/reinterpret_cast), [std::bit_cast](https://en.cppreference.com/w/cpp/numeric/bit_cast), [std::memcpy](https://en.cppreference.com/w/cpp/string/byte/memcpy), [Union declaration](https://en.cppreference.com/w/cpp/language/union)
- **Prerequisites:** casts-and-qualifiers, object-lifetime-and-storage

When programmers complain that an optimizing compiler "broke" working debug code at `-O2`, the underlying culprit is almost always **undefined behavior (UB)**—frequently triggered by type punning across unrelated pointers. Understanding what the C++ abstract machine promises, and why it refuses to alias `float*` with `uint32_t*`, separates predictable low-level systems code from ticking time bombs.

## The contract behind undefined behavior and as-if

Under `[intro.abstract]`, a conforming C++ compiler must preserve the observable behavior of any program executing well-defined operations—known as the **as-if rule**. When an operation triggers undefined behavior, the standard imposes zero requirements on the resulting execution.

Crucially, UB is not a local runtime hiccup that merely yields a surprising integer. Optimizing compilers treat UB as **unreachable**: if execution reaches a path that unconditionally violates a rule, the compiler may prove the conditions leading to that path are impossible and delete surrounding branches, hoist loads out of loops, or reorder stores globally—even retroactively *before* the failing line runs.

## The strict aliasing rule in [basic.lval]

To generate fast code without reloading every register after every pointer write, compilers perform **Type-Based Alias Analysis (TBAA)**. Suppose a function takes `float* f` and `std::uint32_t* u`: if the compiler had to assume writing `*u = 0` could overwrite `*f`, it could never cache `*f` in a floating-point register across stores.

Section `[basic.lval]/11` codifies the **strict aliasing rule**. Attempting to access the stored value of an object through a glvalue whose type is unrelated to the object's dynamic type is undefined behavior unless the glvalue's type matches one of these permitted categories:

| Permitted glvalue type | Example access | Why the standard allows it |
| --- | --- | --- |
| Dynamic type (or cv-qualified) | Reading `T` via `const T&` | Direct access matching live object |
| Signed or unsigned variant | Reading `int` via `unsigned int&` | Standard signedness compatibility |
| Aggregate or union containing permitted type | Reading `struct S { int x; }` | Accessing enclosing layout |
| Base class subobject type | Accessing `Derived` via `Base&` | Object-oriented polymorphism |
| `char`, `unsigned char`, or `std::byte` | Inspecting raw object representation | Byte-level serialization and `memcpy` |

> **Mental model.** Pointers in C++ carry **type provenance**, not merely raw virtual addresses. Saying two pointers hold the same address does not authorize accessing memory through a type unrelated to the live object stored there.

> **Standardese.** Notice the exact wording of `[basic.lval]/11`: byte-wise aliasing is granted exclusively to `char`, `unsigned char`, and `std::byte`—**not** `signed char`, `std::int8_t`, or `std::uint8_t` (when `uint8_t` is not guaranteed to be `unsigned char` on every hypothetical platform, though typically an alias). In generic code, use `std::byte` or `unsigned char` explicitly.

## Why pointer casts and union punning fail in C++

Two classic C idioms break silently in C++:

First, **`reinterpret_cast` pointer punning**:

```cpp
// Broken UB: violates strict aliasing in [basic.lval]/11!
float f = 1.0f;
std::uint32_t bits = *reinterpret_cast<std::uint32_t*>(&f);
```

While `reinterpret_cast` itself converts the pointer value (assuming alignment holds), **dereferencing** that `std::uint32_t*` reads an object whose dynamic type is `float` through an unrelated type `std::uint32_t`. At `-O2`, GCC and Clang routinely cache `f` in a register or eliminate stores because TBAA assumes `uint32_t*` and `float*` never alias.

Second, **union type punning**: in C99/C11, writing to one union member and reading another inspects the object representation cleanly. **Standard C++ forbids this** under `[class.union]`: a union holds at most one active member at any instant, and reading an inactive member is undefined behavior (with one narrow exception for the **common initial sequence** of two standard-layout struct members inside a standard-layout union per `[class.mem.general]`):

```cpp
struct HeaderA { int tag; double payload; };
struct HeaderB { int tag; long extra; };
union Packet {
    HeaderA a;
    HeaderB b;
};

int read_common_tag(const Packet& p) noexcept {
    // Valid even if p.b is active: `tag` is in the common initial sequence.
    return p.a.tag;
}
```

> **Pitfall.** Several compilers tolerate union type punning at runtime as a non-standard C compatibility extension, yet reject inactive-member reads immediately in `constexpr` evaluation and make no cross-translation-unit guarantees. Never rely on union punning for bit conversion.

## Safe bit inspection: bit_cast, memcpy, and byte spans

Modern C++ offers clean, zero-overhead primitives that convey intent to the optimizer without violating `[basic.lval]`.

Since C++20, **`std::bit_cast<To>(from)`** (`<bit>`) is the canonical way to reinterpret bits between identically sized trivially copyable types (`sizeof(To) == sizeof(From)`). Better still, `std::bit_cast` is `constexpr` (provided the representation has no indeterminate bits or pointers in constant evaluation) and compiles down to a single register-to-register move:

```cpp
#include <bit>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <span>

constexpr std::uint32_t float_bits(float f) noexcept {
    return std::bit_cast<std::uint32_t>(f);
}
static_assert(float_bits(1.0f) == 0x3f800000u);

std::uint32_t float_bits_pre20(float f) noexcept {
    std::uint32_t out = 0;
    std::memcpy(&out, &f, sizeof(out)); // Valid in every C++ standard
    return out;
}

std::byte first_byte_of(const double& d) noexcept {
    auto bytes = std::as_bytes(std::span{&d, 1});
    return bytes[0];
}
```

Before C++20, **`std::memcpy`** into an appropriately typed destination object has always been valid and optimizes away completely into the same register move under GCC, Clang, and MSVC. When you merely want to hash, checksum, or serialize raw bytes, `std::as_bytes(std::span{&obj, 1})` hands you a `std::span<const std::byte>` that obeys `[basic.lval]/11` natively.

## Common UB traps beyond aliasing

Strict aliasing is only one member of the UB family that aggressively transforms optimized builds:

- **Signed integer overflow:** Unlike unsigned arithmetic (which wraps modulo 2^N), signed overflow (`INT_MAX + 1`) is UB (`[expr.pre]`). Compilers optimize `x + 1 > x` to unconditional `true` for signed `int`, breaking overflow checks written *after* the addition.
- **Post-dereference null checks:** Writing `int v = *p; if (!p) return;` proves to the optimizer that `p` was non-null at line 1 (otherwise UB already occurred), letting the compiler delete the `if (!p)` guard entirely.
- **Out-of-bounds pointer arithmetic:** Forming a pointer outside `[begin, end]` (even `begin - 1` or `end + 1`, and even without dereferencing!) triggers UB under `[expr.add]`. Only the one-past-the-end pointer `end` may be formed, never dereferenced.

> **Pitfall.** Checking `if (x + delta < x)` on signed integers to detect overflow invites the optimizer to delete the entire check because signed overflow cannot happen in well-defined C++. Always check bounds *before* performing signed arithmetic, or cast to the unsigned counterpart.

## What to remember

- Undefined behavior is an **optimizer assumption**, not a guaranteed crash: once a path invokes UB, surrounding checks and branches can vanish globally.
- Under **`[basic.lval]/11`**, unrelated pointer types cannot alias; only matching types, signed/unsigned pairs, enclosing aggregates/unions, bases, and `char`/`unsigned char`/`std::byte` may view the same object's bytes.
- Replace `*reinterpret_cast<U*>(&t)` and C-style union punning with **`std::bit_cast`** (C++20+), **`std::memcpy`**, or **`std::as_bytes`**.
- Keep `signed char` separate from byte-inspection types (`std::byte` / `unsigned char`) and guard against signed overflow, post-dereference null checks, and out-of-range pointer formation.

## Concept Map Outline

- **Strict Aliasing and UB:** Type-based alias guarantees, undefined behavior optimizer effects, and safe bit reinterpretation.
  - **UB and Optimizer Contract:** How the as-if rule empowers compilers to prune impossible paths.
    - **As-If Rule Guarantees:** Compilers preserve observable behavior only for well-defined program executions.
    - **Retroactive Dead-Code Elimination:** Assuming UB never occurs lets optimizers delete earlier null checks or bounds tests.
  - **Strict Aliasing Rule:** Restrictions in [basic.lval] enabling type-based alias analysis.
    - **Type Provenance vs Address:** Matching addresses alone never authorizes reading an object through an unrelated pointer.
    - **Permitted Aliasing Categories:** Dynamic type, signedness variants, enclosing aggregates, bases, and byte types.
    - **Byte Types Without signed char:** Only char, unsigned char, and std::byte may inspect arbitrary object representations.
  - **Broken C Punning Idioms:** Legacy patterns that break standard C++ object semantics.
    - **reinterpret_cast Dereference:** Casting float* to uint32_t* and dereferencing violates [basic.lval] under TBAA.
    - **Union Type Punning UB:** Reading an inactive union member is UB in C++ except for common initial sequences.
  - **Safe Bit Inspection:** Zero-overhead standard primitives that satisfy the abstract machine.
    - **C++20 std::bit_cast:** Constexpr-friendly value reinterpretation between equal-sized trivially copyable types.
    - **Portable std::memcpy:** Copies bytes into a live destination object while compiling to register moves.
    - **std::as_bytes Spans:** Exposes std::span<const std::byte> views safely for hashing and serialization.
  - **Neighboring UB Hazards:** Arithmetic and pointer traps unrelated to aliasing.
    - **Signed Integer Overflow:** Unlike unsigned wraparound, signed overflow allows algebraic simplification of guards.
    - **Out-of-Bounds Pointer Math:** Forming any pointer beyond [begin, end] is UB even without dereferencing.

## Standardese Quiz Questions

### Question 1 [warmup] ([bit.cast])

Which modern C++20 utility reinterprets the bit pattern of a float as a std::uint32_t safely and supports constexpr evaluation?

A. std::launder<std::uint32_t>(f)
B. *reinterpret_cast<std::uint32_t*>(&f)
C. std::assume_aligned<4>(f)
D. std::bit_cast<std::uint32_t>(f)

**Answer (D):** std::bit_cast<std::uint32_t>(f)

**Why:** std::bit_cast<To>(from) in <bit> creates a new To value from the object representation of from without aliasing pointers, requires matching sizes and trivially copyable types, and works in constexpr.

### Question 2 [warmup] ([class.union], [basic.life])

Why does reading an inactive member of a union (such as writing u.f = 1.0f; and reading u.i;) invoke undefined behavior in C++?

```cpp
union Pun { float f; std::uint32_t u; };
Pun p{ .f = 1.0f };
std::uint32_t bits = p.u;
```

A. At most one union member can be active at a time in C++, so reading an inactive member breaks object lifetime rules
B. Unions cannot store floating-point and integer types together
C. Designated initializers always zero-initialize the wrong member
D. Reading p.u violates alignment rules on 64-bit targets

**Answer (A):** At most one union member can be active at a time in C++, so reading an inactive member breaks object lifetime rules

**Why:** Unlike C99/C11 where union type punning is valid, C++ unions ([class.union]) have at most one active member whose lifetime is active. Accessing p.u when p.f is active is UB (save for the narrow common-initial-sequence rule for standard-layout structs).

### Question 3 [tricky] ([intro.abstract], [expr.unary.op])

In the function below, why can an optimizing compiler legally delete the `if (!p)` check?

```cpp
int inspect(int* p) {
    int v = *p;
    if (!p) return -1;
    return v;
}
```

A. Pointers passed as function arguments can never be null in C++
B. The compiler caches `int v` in a register before evaluating `!p`
C. Dereferencing *p on line 1 would be UB if p were null, allowing the optimizer to deduce p != nullptr
D. The optimizer treats return -1 as unreachable for non-negative integers

**Answer (C):** Dereferencing *p on line 1 would be UB if p were null, allowing the optimizer to deduce p != nullptr

**Why:** Because *p precedes if (!p), any execution with p == nullptr already triggered undefined behavior. Under [intro.abstract], the optimizer assumes UB never happens, proves p != nullptr after line 1, and removes the dead branch.

### Question 4 [tricky] ([expr.add])

Assuming `int buf[4]{};`, which pointer formation alone triggers undefined behavior even if you never dereference the resulting pointer?

```cpp
int buf[4]{1, 2, 3, 4};
```

A. int* end = buf + 4;
B. int* bad = buf + 5;
C. int* first = &buf[0];
D. void* raw = buf;

**Answer (B):** int* bad = buf + 5;

**Why:** Under [expr.add], pointer arithmetic is defined only within the array bounds plus one-past-the-end (buf + 4). Forming buf + 5—or buf - 1—causes undefined behavior immediately upon pointer addition, even without dereferencing.

### Question 5 [standardese] ([basic.lval])

According to [basic.lval]/11, which byte-oriented pointer type is NOT listed as permitted to alias an object of an arbitrary dynamic type like double?

A. char*
B. unsigned char*
C. std::byte*
D. signed char*

**Answer (D):** signed char*

**Why:** Section [basic.lval]/11 explicitly grants byte-level aliasing to char, unsigned char, and std::byte—never signed char! Using signed char* (or int8_t*) to inspect arbitrary object representations violates strict aliasing.

### Question 6 [standardese] ([class.mem.general], [class.union])

Under [class.mem.general], when is reading an inactive member of a standard-layout union well-defined in C++?

```cpp
struct A { int tag; double x; };
struct B { int tag; long y; };
union U { A a; B b; };
```

A. When accessing a member belonging to the common initial sequence of two standard-layout struct members of the union
B. Whenever both struct members have identical total sizeof
C. Only when the union is declared inside an extern "C" block
D. Whenever the member is read through a reinterpret_cast

**Answer (A):** When accessing a member belonging to the common initial sequence of two standard-layout struct members of the union

**Why:** Per [class.mem.general], in a standard-layout union with active member of struct type T1, it is permitted to inspect a non-static data member m of another standard-layout struct member T2 provided m belongs to their common initial sequence (like int tag above).

# Strict aliasing and undefined behavior

> Undefined behavior is a promise you make to the optimizer, not a crash you might get. This page covers the kinds of non-portable behavior, the type-accessibility rule behind strict aliasing, the sanctioned ways to reinterpret bytes, and the pointer rules that compilers quietly rely on.

- **Source:** C++ Atlas (https://cppatlas.com/topics/strict-aliasing-and-undefined-behavior)
- **Track:** Memory model
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [intro.abstract] (https://eel.is/c++draft/intro.abstract), [defns.undefined] (https://eel.is/c++draft/defns.undefined), [basic.lval] (https://eel.is/c++draft/basic.lval), [basic.compound] (https://eel.is/c++draft/basic.compound), [expr.add] (https://eel.is/c++draft/expr.add), [class.union] (https://eel.is/c++draft/class.union), [bit.cast] (https://eel.is/c++draft/bit.cast), [obj.lifetime] (https://eel.is/c++draft/obj.lifetime), [basic.indet] (https://eel.is/c++draft/basic.indet), [expr.const] (https://eel.is/c++draft/expr.const)
- **cppreference links:** [Undefined behavior](https://en.cppreference.com/w/cpp/language/ub), [reinterpret_cast conversion (type aliasing)](https://en.cppreference.com/w/cpp/language/reinterpret_cast), [std::bit_cast](https://en.cppreference.com/w/cpp/numeric/bit_cast), [std::start_lifetime_as](https://en.cppreference.com/w/cpp/memory/start_lifetime_as), [Union declaration](https://en.cppreference.com/w/cpp/language/union), [Pointer arithmetic (additive operators)](https://en.cppreference.com/w/cpp/language/operator_arithmetic)
- **Prerequisites:** object-lifetime-and-storage, object-layout-and-alignment

## The one idea

C++ is specified against an abstract machine. A conforming implementation only has to reproduce the observable behavior of that machine: volatile accesses, the data written to files, and the order of interactive input and output. Undefined behavior marks the executions for which the standard imposes no requirement at all. The optimizer turns that into an assumption. Because a correct program never executes undefined behavior, the compiler may assume yours does not, and it builds its transformations on that assumption.

> **Mental model.** UB is not "the hardware does something odd". It is a contract clause. You promised the compiler that this situation never arises, and the compiler spent that promise on deleting checks, reordering loads and collapsing loops. When the promise is broken, there is no meaningful program left to reason about.

The standard says this explicitly in [intro.abstract]. If an execution contains an undefined operation, there is no requirement on that execution, not even for the operations that came before it. Optimizations really do move effects across the bad operation.

```cpp
int first(int* p) {
  int v = *p;          // if p were null, this would be UB
  if (!p) return -1;   // so the compiler may assume p != nullptr and delete this check
  return v;
}

bool always(int x) {
  return x + 1 > x;    // signed overflow is UB, so GCC -O2 compiles this to "return true"
}
```

The same comparison on `unsigned` has to handle wraparound and is not folded. Signed overflow is undefined, while unsigned arithmetic is defined to wrap modulo two to the power of the bit width.

## Four kinds of "not portable"

The standard distinguishes several categories, and confusing them leads to wrong conclusions.

| Category | What the standard requires | Example |
|---|---|---|
| Implementation-defined | One documented behavior per implementation | `sizeof(int)`, right-shifting a negative value before C++20 |
| Unspecified | One of a set of allowed behaviors, not documented, may vary | evaluation order of function arguments |
| Undefined | Nothing at all | signed overflow, null dereference, data races |
| Ill-formed, no diagnostic required | The program is invalid, but the compiler need not say so | ODR violations, or `constinit` missing from the initializing declaration |

Unspecified behavior is constrained. In `f(g(), h())`, either `g` or `h` runs first, but they do not interleave and nothing else can happen. C++17 also made several famous expressions well-defined by sequencing them. One example is `i = i++ + 2`, because since C++17 the right operand of an assignment is sequenced before the left.

Reading an uninitialized automatic variable is undefined in C++23, except for the narrow case of `unsigned char` and `std::byte` copies. C++26 changes this. Under P2795 such a read becomes erroneous behavior: the variable holds an implementation-chosen value, the implementation is encouraged to diagnose the read, and the optimizer may no longer treat the read as impossible. The attribute `[[indeterminate]]` restores the old semantics where the cost matters. That change is C++26 only.

## The type-accessibility rule

"Strict aliasing" is the folk name for one paragraph of [basic.lval]. It does not talk about pointers at all. It talks about which glvalue types may access an object's stored value.

> **Standardese.** [basic.lval] says that a program which accesses an object through a glvalue whose type is not similar to one of the following has undefined behavior: the object's dynamic type, the signed or unsigned type corresponding to the dynamic type, or `char`, `unsigned char` or `std::byte`. "Similar" means the types match after cv-qualifiers are stripped at every level.

Three things follow from that list.

First, an `int` may be read as `unsigned int`, and a `const int` as `int`. Nothing else of a different type may read it: not `long`, even when `long` has the same size, not `float`, and not a struct whose first member is an `int`. C++20 removed the old wording about aggregates containing the type.

Second, `signed char` is not on the list. C allows every character type, but C++ allows only `char`, `unsigned char` and `std::byte`.

Third, the exemption is one-way. You may inspect any object through a byte glvalue. You may not treat a byte buffer as if it contained an `int` unless an `int` object actually lives there.

```cpp
#include <cstdint>

std::uint32_t bits_bad(float f) {
  return *reinterpret_cast<std::uint32_t*>(&f);   // UB: a float accessed as uint32_t
}

int store_bad() {
  alignas(int) char buf[sizeof(int)] = {};
  *reinterpret_cast<int*>(buf) = 1;               // UB: no int object lives in buf
  return buf[0];
}
```

The reason for the rule is performance. If a store through an `int*` cannot modify a `float`, the compiler can keep `float` values in registers across that store without reloading them. GCC enables this assumption from `-O2`, and Clang whenever it optimizes. The flag `-fno-strict-aliasing` turns it off for code that cannot be fixed.

## Why punning through a union fails in C++

In C, writing one union member and reading another reinterprets the bytes. C99 and C11 say so in a footnote. In C++, a union has at most one active member, and reading any other member reads an object outside its lifetime. That is undefined, and constant evaluation rejects it.

```cpp
#include <cstdint>
union U { float f; std::uint32_t u; };

constexpr std::uint32_t pun(float v) {
  U x;
  x.f = v;        // f becomes the active member
  return x.u;     // UB: u is not within its lifetime; a constant expression rejects this
}
```

GCC documents union punning as supported at run time, and Clang behaves the same way. That is a promise from the vendor, not from the language, and it does not hold inside `constexpr` code. One narrow exception is in the standard. If the union holds standard-layout structs that share a common initial sequence of members, you may read those shared members through the inactive alternative. This is the "tagged header" pattern.

## The sanctioned tools

There are three portable ways to get a value of type `To` from the bytes of something else.

`std::memcpy` copies the object representation into a real object of the destination type. Compilers recognize small fixed-size copies and emit a single register move, so this costs nothing at `-O2`.

`std::bit_cast<To>(from)` was added in C++20. It requires both types to be trivially copyable and of the same size, and it is `constexpr` when neither type contains a union, pointer, pointer to member, volatile or reference member. Unlike the `memcpy` idiom, it does not need `To` to be default-constructible.

`std::start_lifetime_as<T>(p)` was added in C++23. It is for the case where the bytes already sit in suitable storage, such as a network buffer or a mapped file. It creates a `T` there whose value is formed from those bytes and returns a pointer to it, without copying anything and without running a constructor. `T` must be an implicit-lifetime type.

```cpp
#include <bit>
#include <cstdint>
#include <cstring>

constexpr std::uint32_t bits(float f) { return std::bit_cast<std::uint32_t>(f); }
static_assert(bits(1.0f) == 0x3f800000);            // IEEE-754 binary32 assumed

std::uint32_t bits_memcpy(float f) {
  std::uint32_t u;
  std::memcpy(&u, &f, sizeof u);                    // well-defined; compiles to one move
  return u;
}
```

> **Pitfall.** `std::launder` is not a punning tool. It only finds an object that already exists at an address, with the type you ask for. Using it to read a `float` as an `int` is exactly as undefined as the `reinterpret_cast` it wraps.

## Provenance and pointer arithmetic

A pointer value in C++ is more than an address. It points to a particular object, or past the end of one, and the operations you may perform depend on that object. Pointer arithmetic is defined only within an array, treating a non-array object as an array of one element. You may form the pointer one past the last element and compare it, but not dereference it. Forming any pointer further out, including one before the first element, is undefined even if you never dereference it.

```cpp
int a[4]{};
int* end = a + 4;    // OK: one past the end
bool b = end != a;   // OK
int* q = a - 1;      // UB at the moment it is computed, even though it is never used
```

Comparing pointers into unrelated objects with `<` gives an unspecified result. `std::less` is guaranteed to provide a strict total order, so use it for pointer keys.

`reinterpret_cast` changes the pointed-to object only between pointer-interconvertible objects. Those are an object and itself, a union and each of its members, and a standard-layout class object and its first non-static data member, or a base class subobject when the class has no data members. For any other pair, the cast changes the pointer's type but it still points to the original object. That is why a pointer to an array's first element, cast to the type of an object living inside the array, needs `std::launder`. Two objects that happen to share an address are not thereby interchangeable.

## Constant evaluation diagnoses UB

The standard says that an expression which would perform an operation with undefined behavior, as specified in the core language clauses, is not a core constant expression. A `constexpr` variable, a `static_assert` or a template argument that needs such an expression is ill-formed, and the compiler must diagnose it. That turns the compiler into a UB checker for any code you can run at compile time.

```cpp
#include <climits>
constexpr int inc(int i) { return i + 1; }

constexpr int a = inc(INT_MAX);   // ill-formed: overflow is diagnosed
int b = inc(INT_MAX);             // compiles; dynamic initialization, UB at run time
```

There are two limits. Undefined behavior that the library specifies, such as violating a precondition of a standard function, need not be diagnosed. Compilers also have gaps. In testing for this page, Clang 21 rejected forming `a - 1` inside a constant expression, while GCC 16 accepted it without a diagnostic. Treat constant evaluation as a strong test, not a proof.

## What to remember

- UB is an assumption the optimizer may use, and it can affect code that runs before the bad operation.
- Keep implementation-defined (documented), unspecified (one of several outcomes), undefined (no requirement) and ill-formed NDR (invalid but silent) apart.
- An object may only be accessed through its own type, its signed or unsigned counterpart, or `char`, `unsigned char` and `std::byte`. `signed char` is not exempt, and the exemption does not work in reverse.
- Union punning is UB in C++, but defined in C. GCC and Clang allow it at run time as an extension, never in constant evaluation.
- Reinterpret bytes with `memcpy`, `std::bit_cast` (C++20) or `std::start_lifetime_as` (C++23).
- Pointer arithmetic stays within an array plus one past the end. Merely forming any other pointer is UB.
- `reinterpret_cast` only retargets between pointer-interconvertible objects. Otherwise use `std::launder` or the pointer that creation returned.
- Core-language UB in a constant expression is a compile error, which makes `constexpr` tests a cheap UB detector.
- C++26 turns uninitialized reads into erroneous behavior, with `[[indeterminate]]` as the opt-out.

## Concept Map Outline

- **Strict aliasing and UB:** UB is an assumption the optimizer may make; the aliasing rule is one of the assumptions it relies on most.
  - **Abstract machine:** Implementations only need to reproduce the observable behavior of the abstract machine.
    - **No requirements:** An execution containing UB has no requirements, even for operations before the UB.
    - **Optimizer assumptions:** Null checks after a dereference and x + 1 > x on signed int can be folded away.
  - **Behavior categories:** Four distinct kinds of non-portable behavior.
    - **Implementation-defined:** One behavior, documented by the implementation, such as sizeof(int).
    - **Unspecified:** One of several allowed outcomes, undocumented, such as function argument evaluation order.
    - **Ill-formed NDR:** The program is invalid but needs no diagnostic, such as an ODR violation.
    - **Erroneous behavior:** C++26 only: uninitialized reads give an implementation value, with [[indeterminate]] to opt out.
  - **Type-accessibility rule:** [basic.lval] restricts which glvalue types may access an object's stored value.
    - **Allowed types:** The dynamic type (up to cv), its signed or unsigned counterpart, and char, unsigned char, std::byte.
    - **signed char excluded:** Unlike C, C++ does not let signed char access arbitrary objects.
    - **One-way exemption:** Bytes may view any object, but a byte buffer cannot be read as an int that is not there.
  - **Punning:** Reinterpreting bytes as another type needs a sanctioned tool.
    - **Union punning is UB:** Only the active member is alive; C defines punning, and GCC allows it at run time as an extension.
    - **memcpy and bit_cast:** memcpy copies representations; bit_cast (C++20) needs equal size and trivially copyable types.
    - **start_lifetime_as:** C++23: makes an implicit-lifetime T from bytes already in place, with no copy.
  - **Pointer provenance:** A pointer points to a specific object; its arithmetic and casts depend on that object.
    - **Array bounds:** Arithmetic stays within the array or one past the end; forming any other pointer is UB.
    - **Pointer-interconvertible:** Only union and member, or standard-layout object and first member, retarget via reinterpret_cast.
    - **Unrelated comparison:** Built-in < on unrelated pointers is unspecified; std::less gives a total order.
  - **Constant evaluation:** Core-language UB makes an expression non-constant, so it must be diagnosed.
    - **constexpr as UB checker:** A static_assert over a constexpr test turns overflow, bad reads and bounds errors into compile errors.
    - **Limits:** Library-precondition UB need not be diagnosed, and compilers have gaps.

## Standardese Quiz Questions

### Question 1 [warmup] ([class.union], [basic.life], [expr.const])

Ignoring compiler extensions, what does standard C++23 say about `bits(1.0f)`?

```cpp
#include <cstdint>
union U { float f; std::uint32_t u; };

std::uint32_t bits(float v) {
  U x;
  x.f = v;
  return x.u;
}
```

A. Well-defined: it returns the IEEE-754 bit pattern, as it does in C
B. Implementation-defined: the result depends on the floating-point format
C. Undefined behavior: `u` is not the active member, so it is read outside its lifetime
D. Unspecified: it returns some valid `uint32_t` value

**Answer (C):** Undefined behavior: `u` is not the active member, so it is read outside its lifetime

**Why:** In C++ a union has at most one active member. After `x.f = v`, only `f` is within its lifetime, and reading `x.u` is undefined. In a constant expression GCC and Clang both reject it as reading an inactive member. C does define this reinterpretation, and GCC documents it as a run-time extension in C++, which is why the first option is tempting, but neither makes it standard C++. Use `std::bit_cast<std::uint32_t>(v)` instead.

### Question 2 [warmup] ([bit.cast])

Which set of requirements does `std::bit_cast<To>(from)` (C++20) impose on `To` and `From`?

A. Same size, and both trivially copyable
B. Same size and same alignment
C. Same size, both trivially copyable, and `To` default-constructible
D. Both standard-layout

**Answer (A):** Same size, and both trivially copyable

**Why:** `std::bit_cast` participates in overload resolution only when `sizeof(To) == sizeof(From)` and both types are trivially copyable. It creates its result object directly, so, unlike the `memcpy` idiom, which needs a destination object to copy into, it does not require `To` to be default-constructible. Alignment is irrelevant because the result is a fresh value, and standard-layout is not required.

### Question 3 [warmup] ([expr.pre], [basic.fundamental], [intro.abstract])

What may a conforming optimizing compiler emit for `f`?

```cpp
bool f(int x) {
  return x + 1 > x;
}
```

A. It must emit a comparison, because `x == INT_MAX` has to return `false`
B. It may emit `return true;`
C. It must wrap around like unsigned arithmetic, because the representation is two's complement since C++20
D. It must trap when `x == INT_MAX`

**Answer (B):** It may emit `return true;`

**Why:** Signed integer overflow is undefined, so the compiler may assume `x + 1` never overflows, and then `x + 1 > x` is always true. GCC at `-O2` emits exactly `return true`. C++20 did mandate two's-complement representation, but it left overflow in arithmetic undefined, which is why the third option is wrong. Only the `unsigned` version is required to handle wraparound.

### Question 4 [tricky] ([basic.lval], [intro.object], [expr.reinterpret.cast])

Is this program well-defined?

```cpp
int main() {
  alignas(int) char buf[sizeof(int)] = {};
  int* p = reinterpret_cast<int*>(buf);
  *p = 1;
  return buf[0];
}
```

A. Yes: `char` may alias anything, and the buffer is correctly aligned
B. Yes, but `buf[0]` is implementation-defined because of endianness
C. Ill-formed: `reinterpret_cast` from `char*` to `int*` is not allowed
D. No: it is undefined behavior, because no `int` object exists in `buf`, and the character-type exemption does not work in reverse

**Answer (D):** No: it is undefined behavior, because no `int` object exists in `buf`, and the character-type exemption does not work in reverse

**Why:** The aliasing rule lets you access an object of *any* type through a `char`, `unsigned char` or `std::byte` glvalue. It does not let you access a `char` array through an `int` glvalue. `buf` is an array of `char`, not `unsigned char` or `std::byte`, so it does not even provide storage for an `int`. The fix is to declare the buffer as `unsigned char` or `std::byte`, use `std::construct_at` or placement new, and access the `int` through the returned pointer, or simply to `memcpy` into an `int`.

### Question 5 [tricky] ([expr.add], [basic.compound])

Which numbered line, if any, has undefined behavior? None of the pointers is ever dereferenced.

```cpp
void f() {
  int a[4]{};
  int* end = a + 4;    // (1)
  bool b = end != a;   // (2)
  int* q = a - 1;      // (3)
  (void)b; (void)q;
}
```

A. None: pointer arithmetic is only undefined if you dereference the result
B. (1), because `a + 4` points outside the array
C. (3), because forming a pointer before the first element is undefined even without a dereference
D. (2) and (3)

**Answer (C):** (3), because forming a pointer before the first element is undefined even without a dereference

**Why:** Pointer arithmetic is defined only for results from the first element up to one past the last. `a + 4` is the one-past-the-end pointer, which may be formed and compared but not dereferenced. `a - 1` falls outside that range, so computing it is already undefined. The 'only dereference is UB' intuition comes from flat-address-space hardware, but the abstract machine does not work that way. Clang rejects line (3) in a constant expression.

### Question 6 [tricky] ([expr.const], [basic.start.static], [expr.pre])

What does the standard say about declarations (1) and (2)?

```cpp
#include <climits>
constexpr int g(int i) { return i + 1; }

constexpr int a = g(INT_MAX);   // (1)
int b = g(INT_MAX);             // (2)
```

A. Both are ill-formed, because `g(INT_MAX)` is never a constant expression
B. (1) is ill-formed and must be diagnosed; (2) compiles and has undefined behavior when it runs
C. Both are undefined behavior, and the compiler is not required to diagnose either
D. Both are well-defined and wrap to `INT_MIN`

**Answer (B):** (1) is ill-formed and must be diagnosed; (2) compiles and has undefined behavior when it runs

**Why:** An expression that would perform core-language undefined behavior is not a core constant expression, so the `constexpr` variable in (1) has an invalid initializer and must be diagnosed. For (2), the implementation tries constant initialization, fails, and falls back to dynamic initialization at program start, and that dynamic initialization overflows, which is undefined at run time. Being `constexpr` does not make a function constant-only, which is why 'both ill-formed' is wrong.

### Question 7 [standardese] ([basic.lval], [conv.qual])

An object has dynamic type `int`. Accessing its stored value through a glvalue of which type is undefined behavior under C++23 [basic.lval]?

A. `unsigned int`
B. `const volatile int`
C. `char`
D. `signed char`

**Answer (D):** `signed char`

**Why:** The permitted types are those similar to the dynamic type, the signed or unsigned type corresponding to the dynamic type, and `char`, `unsigned char` or `std::byte`. `unsigned int` is the corresponding unsigned type, `const volatile int` is similar to `int`, and `char` is explicitly listed. `signed char` is not on the list, so reading an `int` through it is undefined. C's rule covers all character types, which is why this one surprises people.

### Question 8 [standardese] ([expr.ass], [intro.execution])

Under C++17 and later, what is the value of `i` after the assignment?

```cpp
int i = 1;
i = i++ + 2;
```

A. 3
B. Undefined behavior: `i` is modified twice without sequencing
C. Unspecified: either 3 or 4
D. 4

**Answer (A):** 3

**Why:** Since C++17 (P0145), the right operand of an assignment is sequenced before the left operand, and the assignment itself takes effect after both. So `i++` yields 1 and its increment completes, then `1 + 2` is assigned and `i` becomes 3. Before C++17, the two modifications were unsequenced and this was undefined, which is the folklore answer. GCC 16 still emits a `-Wsequence-point` warning here even in C++23 mode, but the program prints 3.

# Atomics and memory ordering

> How C++ defines memory locations, data races, happens-before graphs, acquire-release synchronization, store buffering, and fences.

- **Source:** C++ Atlas (https://cppatlas.com/topics/atomics-and-memory-ordering)
- **Track:** Memory model
- **Estimated reading time:** 11 minutes
- **ISO C++ clauses:** [intro.memory] (https://eel.is/c++draft/intro.memory), [intro.races] (https://eel.is/c++draft/intro.races), [atomics.order] (https://eel.is/c++draft/atomics.order), [atomics.types.generic] (https://eel.is/c++draft/atomics.types.generic), [atomics.fences] (https://eel.is/c++draft/atomics.fences), [atomics.ref.generic] (https://eel.is/c++draft/atomics.ref.generic)
- **cppreference links:** [Memory model](https://en.cppreference.com/w/cpp/language/memory_model), [std::atomic](https://en.cppreference.com/w/cpp/atomic/atomic), [std::memory_order](https://en.cppreference.com/w/cpp/atomic/memory_order), [std::atomic_ref](https://en.cppreference.com/w/cpp/atomic/atomic_ref), [std::atomic_thread_fence](https://en.cppreference.com/w/cpp/atomic/atomic_thread_fence), [std::atomic::compare_exchange_weak](https://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange)
- **Prerequisites:** object-lifetime-and-storage, evaluation-order

Locks protect critical sections at the cost of kernel waits or contention. Lock-free programming swaps coarse mutual exclusion for `std::atomic<T>` and explicit **memory ordering constraints**—contracts governing both how the compiler may reorder instructions and which hardware memory barriers must synchronize store buffers across cores.

## Memory locations, bit-fields, and data races

Thread safety in C++ begins at the granularity of a **memory location** (`[intro.memory]`). A memory location is either an object of scalar type (`int`, `double`, pointer) or a maximal sequence of adjacent non-zero-length bit-fields.

Two threads may access distinct memory locations concurrently with zero synchronization. Adjacent scalar struct members (`int a; int b;`) occupy separate memory locations, whereas adjacent non-zero bit-fields share a **single** memory location because CPUs update them via non-atomic read-modify-write instructions on the enclosing machine word:

```cpp
struct Flags {
    unsigned rx_ready : 4;
    unsigned          : 0; // Zero-width bit-field starts a new memory location
    unsigned tx_ready : 4;
};
```

Without the `: 0` separator, one thread writing `f.rx_ready = 1` while another writes `f.tx_ready = 2` triggers a **data race**. Under `[intro.races]`, two conflicting accesses (at least one write, at least one non-atomic) with no happens-before ordering cause **undefined behavior**—not merely a torn read.

When existing non-atomic aligned data needs temporary atomic access during a parallel phase without changing its stored type permanently, C++20 provides `std::atomic_ref<T>` (`[atomics.ref.generic]`), provided no non-atomic access overlaps the lifetime of the `atomic_ref` usage.

> **Standardese.** Per `[intro.races]`, a data race on any non-atomic variable poisons the entire execution with undefined behavior—even on architectures where aligned word reads and writes appear atomic at the assembly level.

## Sequenced-before, synchronizes-with, and happens-before

The C++ memory model guarantees visibility across threads by composing three partial-order relations:

- **Sequenced-before:** evaluation order within a single thread.
- **Synchronizes-with:** an inter-thread edge formed when an atomic release store (or release fence + relaxed store) writes a value read by an atomic acquire load (or relaxed load + acquire fence).
- **Happens-before:** the transitive closure of sequenced-before and synchronizes-with.

```text
Thread 1 (Producer)                        Thread 2 (Consumer)
  payload = 42;
       │  sequenced-before
       ▼
  ready.store(true, release) ──synchronizes-with──▶ while (!ready.load(acquire))
                                                           │  sequenced-before
                                                           ▼
                                                     assert(payload == 42);
```

Because `payload = 42` is sequenced-before `ready.store(true, release)`, and the acquire loop reads that `true` value, `payload = 42` **happens-before** `assert(payload == 42)`. Notice that a release-acquire chain also extends through **release sequences**: if intermediate threads perform atomic read-modify-write operations (`fetch_add`, `exchange`, `compare_exchange`) on `ready` with any ordering (even `relaxed`), an acquire load reading the final value in that modification chain still synchronizes with the initial release store (`[intro.races]`).

> **Mental model.** Release-acquire synchronization does not "flush CPU caches." It erects a one-way happens-before bridge: ordinary writes before a release store cannot sink past it, and ordinary reads after an acquire load cannot hoist ahead of it.

## The memory_order spectrum compared

Every `std::atomic` operation accepts one of the `std::memory_order` modes (`std::memory_order_seq_cst` by default):

| Memory order | Atomicity | Surrounding reordering constraints | Cross-thread total order |
| --- | --- | --- | --- |
| `relaxed` | Indivisible RMW and reads | None for unrelated memory accesses | Single atomic's modification order only |
| `acquire` | Indivisible read or RMW | Prevents later reads/writes hoisting ahead of load | Pairwise with matching `release` |
| `release` | Indivisible store or RMW | Prevents earlier reads/writes sinking past store | Pairwise with matching `acquire` |
| `acq_rel` | Indivisible RMW | Combines `acquire` and `release` on RMWs | Pairwise on read and write sides |
| `seq_cst` | Indivisible load, store, or RMW | Full `acquire`/`release` semantics plus global order | Single total modification order `S` |

Note that `memory_order::consume` (intended for hardware data-dependency ordering) has been discouraged since C++17; compilers treat it identically to `acquire`.

## Store buffering and why acquire-release is not seq_cst

Developers often assume `release` on stores paired with `acquire` on loads forbids all counter-intuitive outcomes. The **Store Buffering** litmus test proves otherwise—even on strongly ordered x86-64 CPUs!

Suppose `std::atomic<int> x{0}, y{0};` start at zero:

- **Thread 1:** `x.store(1, release); int r1 = y.load(acquire);`
- **Thread 2:** `y.store(1, release); int r2 = x.load(acquire);`

Can **both `r1 == 0` and `r2 == 0`** occur? **Yes.** Release forbids prior writes from sinking past the store, and acquire forbids subsequent reads from hoisting ahead of the load—yet **neither** prevents a following acquire load from moving *before* an earlier release store into a core's local store buffer! Each core buffers its own `1` store locally while its read misses the peer's buffer and observes `0`.

Replacing those operations with `std::memory_order::seq_cst` forces a single global order `S` across all `seq_cst` operations, making `r1 == 0 && r2 == 0` impossible.

> **Pitfall.** Sequential consistency holds **only** among `seq_cst` operations. Mixing `relaxed` or `acquire`/`release` operations into a `seq_cst` protocol breaks the global `S` ordering guarantees you relied on to prevent store-buffering anomalies.

## Compare-exchange loops and fences

Read-modify-write algorithms frequently build custom transitions using `compare_exchange_weak` or `compare_exchange_strong`:

```cpp
#include <atomic>

void atomic_update_max(std::atomic<int>& target, int candidate) noexcept {
    int current = target.load(std::memory_order::relaxed);
    while (current < candidate &&
           !target.compare_exchange_weak(
               current, candidate,
               std::memory_order::release,
               std::memory_order::relaxed)) {
        // On failure, `current` is reloaded with target's latest value.
    }
}
```

Use `compare_exchange_weak` inside retry loops because architectures with load-linked/store-conditional (ARM, POWER) may fail spuriously without extra retry loops inside the instruction sequence; use `compare_exchange_strong` for single-shot state flips where looping would cost extra boilerplate. Under C++17+, the failure memory order only needs to avoid `release` and `acq_rel` (`[atomics.types.operations]`).

When a reader loops many times checking a relaxed flag and only consumes shared data once ready, **`std::atomic_thread_fence`** avoids executing acquire barriers on every failed iteration:

```cpp
#include <atomic>

std::atomic<int> state{0};
int shared_data = 0;

void fence_publish() {
    shared_data = 99;
    std::atomic_thread_fence(std::memory_order::release);
    state.store(1, std::memory_order::relaxed);
}

int fence_consume() {
    if (state.load(std::memory_order::relaxed) == 1) {
        std::atomic_thread_fence(std::memory_order::acquire);
        return shared_data;
    }
    return 0;
}
```

> **Pitfall.** `std::atomic<BigStruct>` compiles quietly for arbitrary trivially copyable structs by falling back to an internal mutex shard table. Always verify `std::atomic<T>::is_always_lock_free` with `static_assert` when targeting real-time or lock-free paths.

## What to remember

- Two threads writing adjacent non-zero bit-fields share **one memory location** and create data-race UB unless separated by `: 0` or synchronized.
- **`relaxed`** guarantees atomicity and single-variable modification order (ideal for pure counters) without synchronizing surrounding non-atomic memory.
- Pair **`release`** stores with **`acquire`** loads to form `synchronizes-with` edges that carry non-atomic payload writes via `happens-before`.
- **`acquire`/`release`** still permits Store Buffering (`r1 == 0 && r2 == 0`); reach for **`seq_cst`** when a single global total order across distinct atomics is required.
- Prefer **`compare_exchange_weak`** in retry loops and verify **`is_always_lock_free`** before assuming hardware atomic instructions.

## Concept Map Outline

- **Atomics and Memory Ordering:** Abstract machine synchronization guarantees connecting C++ threads, compilers, and CPU store buffers.
  - **Memory Locations and Races:** Smallest units of storage accessible independently across concurrent threads.
    - **Scalars vs Bit-Fields:** Adjacent scalars are independent locations while adjacent non-zero bit-fields share one.
    - **Zero-Width Bit-Field Split:** Inserting an unnamed : 0 bit-field separates neighboring fields into distinct locations.
    - **Data Race Undefined Behavior:** Unordered conflicting accesses with one non-atomic write invalidate the whole program.
  - **Happens-Before Relations:** Mathematical ordering edges proving when one thread observes another's writes.
    - **Sequenced-Before Order:** Intra-thread evaluation ordering established within a single execution stream.
    - **Synchronizes-With Edge:** Inter-thread link created when an acquire load reads a release store.
    - **Release Sequences:** Chained atomic RMW operations preserve synchronization back to the initial release store.
  - **Memory Order Spectrum:** Six ordering tags balancing barrier cost against cross-thread guarantees.
    - **Relaxed Counters:** Guarantees indivisible operations and modification order without ordering nearby memory.
    - **Acquire-Release Pairwise:** Prevents earlier writes sinking past release and later reads hoisting above acquire.
    - **Seq-Cst Global Total Order:** Enforces one consistent global order S across all seq_cst atomic operations.
  - **Litmus Tests and Hardware:** Why hardware store buffers break naive intuition without fences.
    - **Store Buffering Anomaly:** Acquire-release allows both cores to read zero because store buffers delay writes.
    - **Lock-Free Hardware Checks:** Verify is_always_lock_free so large structs do not silently fall back to hidden mutexes.
  - **CAS Loops and Fences:** Idiomatic lock-free algorithms built from compare-exchange and standalone barriers.
    - **Weak vs Strong CAS:** Prefer compare_exchange_weak inside retry loops to avoid redundant LL/SC checks.
    - **atomic_thread_fence Pairing:** Release and acquire fences synchronize relaxed atomics only on the fast exit path.

## Standardese Quiz Questions

### Question 1 [warmup] ([atomics.order], [intro.races])

If 8 threads solely increment a shared telemetry counter `counter.fetch_add(1, order)` without publishing any non-atomic data alongside it, which memory order suffices for exact totals?

A. std::memory_order::relaxed
B. std::memory_order::acquire
C. std::memory_order::acq_rel
D. std::memory_order::seq_cst

**Answer (A):** std::memory_order::relaxed

**Why:** Every std::atomic read-modify-write operation is indivisible and obeys the single-object modification order regardless of memory_order. Because no surrounding non-atomic writes need ordering, relaxed suffices without losing counts.

### Question 2 [warmup] ([atomics.types.operations])

Why does `compare_exchange_weak` exist alongside `compare_exchange_strong`?

A. compare_exchange_weak uses non-atomic loads for better throughput
B. compare_exchange_weak does not reload the expected parameter upon failure
C. compare_exchange_weak may fail spuriously on LL/SC architectures, avoiding an internal retry loop when you are already inside a while loop
D. compare_exchange_strong cannot use memory_order::seq_cst

**Answer (C):** compare_exchange_weak may fail spuriously on LL/SC architectures, avoiding an internal retry loop when you are already inside a while loop

**Why:** On LL/SC architectures (such as ARM and POWER), compare_exchange_weak maps directly to a single LL/SC attempt that can fail spuriously due to interrupts or cache contention. Inside a CAS loop, letting the outer while loop retry avoids redundant inner branches.

### Question 3 [tricky] ([atomics.order])

Given `std::atomic<int> x{0}, y{0};`, Thread 1 runs `x.store(1, release); r1 = y.load(acquire);` while Thread 2 runs `y.store(1, release); r2 = x.load(acquire);`. Can `r1 == 0 && r2 == 0` occur?

```cpp
std::atomic<int> x{0}, y{0};
// Thread 1: x.store(1, std::memory_order::release); int r1 = y.load(std::memory_order::acquire);
// Thread 2: y.store(1, std::memory_order::release); int r2 = x.load(std::memory_order::acquire);
```

A. No, because release and acquire guarantee sequential consistency
B. Yes—hardware store buffers allow each thread's acquire load to execute before its own buffered release store becomes visible globally
C. No, at least on x86-64 CPUs because TSO forbids reordering
D. Yes, because accessing two separate atomics without a mutex is undefined behavior

**Answer (B):** Yes—hardware store buffers allow each thread's acquire load to execute before its own buffered release store becomes visible globally

**Why:** This is the Store Buffering (SB) litmus test. Neither release nor acquire forbids a subsequent acquire load from completing before an earlier release store drains from the core's store buffer—even on x86-64. Only memory_order::seq_cst enforces a single total order preventing r1 == 0 && r2 == 0.

### Question 4 [tricky] ([intro.memory], [intro.races])

In `struct Packet { unsigned a : 4; unsigned b : 4; } p{};`, Thread 1 writes `p.a = 1;` while Thread 2 concurrently writes `p.b = 2;`. What does the C++ standard say?

```cpp
struct Packet { unsigned a : 4; unsigned b : 4; } p{};
// T1: p.a = 1;
// T2: p.b = 2;
```

A. Well-defined because a and b have distinct member names
B. Well-defined as long as p is aligned to 8 bytes
C. Implementation-defined value, never undefined behavior
D. Undefined behavior due to a data race on a single shared memory location

**Answer (D):** Undefined behavior due to a data race on a single shared memory location

**Why:** Under [intro.memory], a maximal sequence of adjacent non-zero-length bit-fields forms a SINGLE memory location. Updating p.a compiles to a non-atomic read-modify-write of the enclosing word, racing directly with Thread 2 unless separated by an unnamed zero-width bit-field (`unsigned : 0;`).

### Question 5 [standardese] ([atomics.types.operations])

In C++17 and later, which `memory_order` values are forbidden as the `failure` ordering argument to `std::atomic::compare_exchange_weak(expected, desired, success, failure)`?

A. memory_order::relaxed and memory_order::consume
B. memory_order::seq_cst when success is memory_order::relaxed
C. memory_order::release and memory_order::acq_rel
D. Only memory_order::seq_cst

**Answer (C):** memory_order::release and memory_order::acq_rel

**Why:** Failure does not write to the atomic object, so [atomics.types.operations] forbids passing memory_order::release or memory_order::acq_rel as the failure order. Note that C++17 (P0418R2) removed the older restriction banning failure order from being stronger than success order.

### Question 6 [standardese] ([atomics.fences])

How do `std::atomic_thread_fence(release)` and `std::atomic_thread_fence(acquire)` synchronize two threads communicating through a `relaxed` atomic `flag`?

```cpp
// T1: data = 42; atomic_thread_fence(release); flag.store(1, relaxed);
// T2: if (flag.load(relaxed) == 1) { atomic_thread_fence(acquire); use(data); }
```

A. A release fence followed by an atomic store X synchronizes with an atomic load reading X followed by an acquire fence
B. Fences only synchronize when paired with seq_cst stores
C. The release fence must appear AFTER flag.store(1, relaxed) on T1
D. Fences cannot establish happens-before edges across relaxed atomics

**Answer (A):** A release fence followed by an atomic store X synchronizes with an atomic load reading X followed by an acquire fence

**Why:** Under [atomics.fences], a release fence A followed by an atomic store X that is read by an atomic load Y followed by an acquire fence B causes fence A to synchronize-with fence B—establishing happens-before from data = 42 to use(data).

# Dynamic allocation with new and delete

> A new-expression is two steps, a call to an allocation function and then initialization, and a delete-expression is the same two steps in reverse. This page follows both steps through exceptions, arrays, placement forms, replacement, class-specific operators and the mismatches that are undefined.

- **Source:** C++ Atlas (https://cppatlas.com/topics/dynamic-allocation-new-and-delete)
- **Track:** Memory model
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [expr.new] (https://eel.is/c++draft/expr.new), [expr.delete] (https://eel.is/c++draft/expr.delete), [basic.stc.dynamic] (https://eel.is/c++draft/basic.stc.dynamic), [basic.stc.dynamic.allocation] (https://eel.is/c++draft/basic.stc.dynamic.allocation), [basic.stc.dynamic.deallocation] (https://eel.is/c++draft/basic.stc.dynamic.deallocation), [new.delete] (https://eel.is/c++draft/new.delete), [new.delete.placement] (https://eel.is/c++draft/new.delete.placement), [replacement.functions] (https://eel.is/c++draft/replacement.functions), [class.free] (https://eel.is/c++draft/class.free)
- **cppreference links:** [new expression](https://en.cppreference.com/w/cpp/language/new), [delete expression](https://en.cppreference.com/w/cpp/language/delete), [operator new, operator new[]](https://en.cppreference.com/w/cpp/memory/new/operator_new), [operator delete, operator delete[]](https://en.cppreference.com/w/cpp/memory/new/operator_delete), [std::nothrow](https://en.cppreference.com/w/cpp/memory/new/nothrow), [std::destroying_delete_t](https://en.cppreference.com/w/cpp/memory/new/destroying_delete_t)
- **Prerequisites:** object-lifetime-and-storage, object-layout-and-alignment

## The one idea

The word `new` names two different things. The **new-expression**, `new T(args)`, is a language construct. The **allocation function**, `operator new`, is an ordinary function that returns raw, uninitialized bytes. A new-expression calls an allocation function to get storage, then initializes an object in that storage, then hands you a pointer to the object. A delete-expression runs the destructor and then calls a **deallocation function**, `operator delete`, to give the bytes back.

> **Mental model.** `new T(args)` is roughly `void* raw = operator new(sizeof(T)); return ::new (raw) T(args);`, plus a hidden cleanup that frees `raw` if the constructor throws. `delete p` is `p->~T(); operator delete(p);`. You can customize the functions; you cannot customize the expressions.

Every rule on this page is about one of those steps: which function the expression picks, what the expression does around the call, or what happens when the two halves are not paired correctly. The lifetime rules for the object itself belong to the topic on object lifetime and storage.

## Allocation, then construction, then cleanup on failure

Since C++17 the call to the allocation function is sequenced before the evaluation of the arguments in the initializer. Before C++17 it was unspecified whether `operator new` ran before or after those arguments were evaluated.

If initialization exits with an exception, the new-expression looks up the deallocation function that matches the allocation function, calls it with the pointer, and lets the exception continue. The object never existed, so no destructor runs, but the memory is returned.

```cpp
#include <cstdio>
#include <cstddef>
#include <new>

struct T {
  T(int) { std::puts("ctor"); throw 1; }
  static void* operator new(std::size_t n) { std::puts("new"); return ::operator new(n); }
  static void operator delete(void* p) { std::puts("delete"); ::operator delete(p); }
};
int f() { std::puts("f"); return 0; }

int main() {
  try { new T(f()); } catch (int) { std::puts("caught"); }
}
// prints: new, f, ctor, delete, caught
```

The automatic cleanup only covers the window inside the expression. Once the expression has produced its pointer, nothing frees the memory unless you write a delete-expression or hand the pointer to an owner such as `std::unique_ptr`, which the topic on smart pointers covers.

The allocation function signals failure by throwing `std::bad_alloc`. Before throwing, the standard versions call the installed `std::new_handler` in a loop, which gives a program the chance to release a cache and retry.

## Arrays and the array cookie

`new T[n]` calls `operator new[]` and requests `n * sizeof(T)` bytes plus an unspecified overhead, which can differ from one call to the next. The pointer you receive is offset from the start of the allocated block by that overhead. If `n` is negative, or so large that the size overflows, the expression throws `std::bad_array_new_length` without calling the allocation function. `new T[0]` is valid and returns a distinct non-null pointer that you may not dereference.

The standard does not say what the overhead is for. In practice it holds the element count, because `delete[] p` must run `n` destructors and the pointer alone does not say what `n` is. The Itanium C++ ABI calls this the array cookie. It stores one when the element type has a non-trivial destructor, or when the class has an `operator delete[]` that takes a size, and stores none for other trivially destructible types. MSVC follows a similar rule.

```text
new S[3], S with a non-trivial destructor, Itanium ABI:

operator new[] returns  ->  [ cookie: 3 ][ S ][ S ][ S ]
the expression returns  ->               ^
delete[] reads the cookie just before this address
```

That layout explains why mismatched forms fail so badly. When there is a cookie, `delete p` on an array pointer destroys one element and passes the wrong address to the deallocation function, while `delete[] p` on a single object reads whatever precedes it as the count. Both are undefined whether or not the type has a destructor.

> **Pitfall.** "It worked for `int`" proves nothing. `int* p = new int[10]; delete p;` usually appears to work because there is no cookie and the allocator ignores the size, but the behavior is undefined, and sized deallocation or AddressSanitizer can expose it.

## Placement forms, matching delete and nothrow

Any extra arguments in `new (a, b) T` are passed to the allocation function after the size, so the expression calls `operator new(sizeof(T), a, b)`. The standard library provides one non-allocating form, `operator new(std::size_t, void*)`, which returns its pointer argument and may not be replaced. That is what people usually mean by placement new.

There is no placement delete-expression. A placement deallocation function, one whose extra parameter types are the same as the allocation function's, is called in exactly one situation: when the constructor throws inside a placement new-expression. If no matching deallocation function exists, nothing is freed.

```cpp
#include <cstdio>
#include <cstddef>
#include <new>

struct T {
  T() { throw 1; }
  static void* operator new(std::size_t n, int) { return ::operator new(n); }
  static void operator delete(void* p, int) { std::puts("placement delete"); ::operator delete(p); }
  static void operator delete(void* p) { std::puts("usual delete"); ::operator delete(p); }
};

int main() {
  try { new (42) T; } catch (int) {}   // prints: placement delete
}
```

`new (std::nothrow) T` calls the `nothrow_t` overload, which returns a null pointer instead of throwing. When the allocation function returns null, the new-expression skips initialization and yields null. The constructor is not covered: if it throws, the exception propagates as usual.

A class-specific `operator new` hides every global form for that class, including the non-allocating placement form. After declaring one, `new (buf) T` no longer compiles; write `::new (buf) T`, which is also why generic code always spells placement new with the leading `::`.

## Sized, aligned and destroying deallocation

C++14 added sized deallocation, `operator delete(void*, std::size_t)`, so an allocator can skip looking up the block size. C++17 added the `std::align_val_t` overloads for over-aligned types, described in the topic on object layout and alignment. The delete-expression chooses among these by a fixed procedure. Destroying deletes win if any are found. Then alignment-aware functions are preferred for over-aligned types. For class-specific functions the unsized one is preferred over the sized one. For the global functions the sized form is chosen when the type is complete, except that for `delete[]` it requires a class with a non-trivial destructor, since only then does the cookie record the count. In the remaining cases the choice is unspecified.

C++20 added **destroying delete**: a class-specific `operator delete` whose first parameter is `T*` and whose second is `std::destroying_delete_t`. When the delete-expression selects it, the expression does not call the destructor. The function receives a pointer to a live object and must destroy it itself. That suits variable-sized objects with a trailing buffer, and hierarchies that dispatch destruction on a stored tag instead of a virtual destructor.

```cpp
#include <cstdio>
#include <new>

struct S {
  ~S() { std::puts("~S"); }
  void operator delete(S* p, std::destroying_delete_t) {
    std::puts("destroying delete");
    p->~S();                 // remove this line and ~S never runs
    ::operator delete(p);
  }
};

int main() { delete new S; }  // prints: destroying delete, ~S
```

Class-specific allocation and deallocation functions are implicitly static members. A delete-expression looks up `operator delete` in the scope of the object's dynamic type when the destructor is virtual, because the lookup is done as part of the deleting destructor. So a derived class's `operator delete` is found even when you delete through a base pointer.

## Mismatches that are undefined

The pairing rules are strict, and the compiler usually cannot check them.

- Memory from `new` must be released by `delete`, memory from `new[]` by `delete[]`, and memory from `malloc` by `free`. Any crossing is undefined.
- Deleting through a pointer to a base class requires a virtual destructor in the base. Without one, `delete base_ptr` is undefined even if the derived class adds no members and has a trivial destructor.
- `delete[]` through a pointer to a base class is undefined even with a virtual destructor. The static and dynamic element types must match.
- Deleting a pointer to an incomplete class type whose complete type has a non-trivial destructor or a class-specific deallocation function was undefined through C++23; C++26 makes it ill-formed.

> **Standardese.** [expr.delete] says that in a single-object delete, if the static type of the object differs from its dynamic type, the static type must be a base class of the dynamic type and must have a virtual destructor, or the behavior is undefined. In an array delete, if the dynamic type differs from the static type, the behavior is undefined.

## Replacing the global operators, and elision

A program may define its own versions of the replaceable global allocation and deallocation functions in [new.delete]. The definitions must be at global scope, not `inline` and not `static`, and they replace the library's versions for the whole program. The default behaviors are specified so that a minimal replacement covers almost everything: the nothrow and array forms are defined to call `operator new(std::size_t)`, and the sized, nothrow and array deallocation forms are defined to call `operator delete(void*)`. The aligned forms are a separate family, so a replacement that wants to see every allocation must also define those.

```cpp
#include <cstdlib>
#include <new>

int calls = 0;
void* operator new(std::size_t n) {
  ++calls;
  if (void* p = std::malloc(n ? n : 1)) return p;
  throw std::bad_alloc{};
}
void operator delete(void* p) noexcept { std::free(p); }
void operator delete(void* p, std::size_t) noexcept { std::free(p); }

int main() {
  void* a = ::operator new[](16);          // default operator new[] calls the one above
  void* b = ::operator new(16, std::nothrow);
  ::operator delete[](a);
  ::operator delete(b, std::nothrow);
  return calls;                            // 2
}
```

A replacement must still meet the library's requirements: a throwing `operator new` throws `std::bad_alloc` on failure and never returns null, and every returned pointer must be suitably aligned and distinct from every other live allocation.

### Allocation elision

C++14 adopted N3664, which lets an implementation omit a call to a replaceable global allocation function made by a new-expression, providing the storage some other way, or extend one allocation to cover another whose lifetime it contains. The permission applies even when you have replaced `operator new` with a function that has side effects. Both GCC 16 and Clang 21 at `-O2` remove the pair in `int* p = new int(1); delete p;`, so a counting replacement such as the one in this section sees zero calls instead of one.

The permission covers only new-expressions. A direct call to `::operator new` is an ordinary function call and is never elided, so benchmarks that count allocations through a replacement should use direct calls or defeat the optimizer. `std::allocator::allocate` is specified to obtain memory from `::operator new` while leaving unspecified when and how often it calls it, which gives library containers the same freedom; libc++ makes use of it.

C++20 builds on the same idea for constant evaluation: a new-expression in a constant expression never calls an allocation function at all, which is what lets `constexpr` code use `std::vector` transiently.

## What to remember

- A new-expression allocates, then initializes; a delete-expression destroys, then deallocates. Since C++17 allocation is sequenced before the initializer's arguments.
- If the constructor throws, the matching deallocation function runs automatically; for placement new it is the placement delete with the same extra parameters, and if none exists nothing is freed.
- `new T[n]` may request extra bytes; the Itanium ABI stores a count cookie when `T` has a non-trivial destructor. Mixing `delete` and `delete[]` is undefined for every type.
- `std::nothrow` only covers allocation; a throwing constructor still throws.
- A class-specific `operator new` hides global placement new; generic code writes `::new`.
- Replacing `operator new(size_t)` and `operator delete(void*)` covers the nothrow, array and sized forms, but not the aligned ones.
- Destroying delete (C++20) receives a live object and must call the destructor itself.
- Deleting through a base pointer needs a virtual destructor; `delete[]` through a base pointer is always undefined.
- Since C++14 allocations made by new-expressions may be elided or merged, even when `operator new` is replaced.

## Concept Map Outline

- **new and delete:** A new-expression allocates then initializes; a delete-expression destroys then deallocates.
  - **The new-expression:** Calls an allocation function for raw bytes, then initializes an object in them.
    - **Sequencing (C++17):** The allocation function is called before the initializer's arguments are evaluated.
    - **Constructor throws:** The matching deallocation function frees the storage; no destructor runs.
    - **std::nothrow:** Allocation failure yields null; a throwing constructor still throws.
    - **new_handler:** Standard operator new calls the installed handler in a loop before throwing bad_alloc.
  - **Arrays:** new T[n] calls operator new[] and may request unspecified extra bytes.
    - **Array cookie:** Itanium stores the count when T has a non-trivial destructor, so delete[] knows n.
    - **bad_array_new_length:** Thrown for a negative or overflowing size, before any allocation function is called.
    - **new T[0]:** Valid; returns a distinct non-null pointer that must not be dereferenced.
  - **Placement forms:** Extra arguments in new (args) T are passed to operator new after the size.
    - **Non-allocating form:** operator new(size_t, void*) returns its argument and cannot be replaced.
    - **Placement delete:** Called only when the constructor throws; it must match the extra parameter types.
    - **Class operator new hides:** A class-specific operator new hides global placement new; write ::new.
  - **Deallocation functions:** The delete-expression picks one by a fixed preference procedure.
    - **Sized (C++14):** Global sized delete is chosen for complete types; for delete[] it needs a non-trivial destructor.
    - **Aligned (C++17):** align_val_t overloads are preferred for over-aligned types.
    - **Destroying delete (C++20):** Takes T* and destroying_delete_t; the expression skips the destructor.
    - **Dynamic-type lookup:** With a virtual destructor, operator delete is found in the dynamic type's scope.
  - **Replacement:** Global definitions of the replaceable functions replace the library's for the whole program.
    - **Minimal set:** Nothrow, array and sized forms default to calling operator new(size_t) or operator delete(void*).
    - **Aligned family:** Aligned overloads do not call the unaligned ones and need their own replacement.
    - **Elision (C++14):** Calls from new-expressions may be omitted or merged, even when replaced.
    - **Direct calls:** Calling ::operator new as a function is never elided.
  - **Undefined mismatches:** Pairing errors the compiler usually cannot detect.
    - **delete vs delete[]:** Crossing the forms, or with malloc and free, is undefined for every type.
    - **Non-virtual base:** delete through a base pointer needs a virtual destructor, even if Derived adds nothing.
    - **delete[] through base:** Undefined whenever the static element type differs from the dynamic one.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.new])

What does this program print?

```cpp
#include <cstdio>
#include <cstddef>
#include <new>

struct T {
  T() { std::puts("ctor"); throw 1; }
  ~T() { std::puts("~T"); }
  static void* operator new(std::size_t n) { std::puts("new"); return ::operator new(n); }
  static void operator delete(void* p) { std::puts("delete"); ::operator delete(p); }
};

int main() {
  try { new T; } catch (int) { std::puts("caught"); }
}
```

A. `new`, `ctor`, `caught`, and the memory leaks
B. `new`, `ctor`, `~T`, `delete`, `caught`
C. `new`, `ctor`, `delete`, `caught`
D. `ctor`, `caught`, because `new` is called only after construction succeeds

**Answer (C):** `new`, `ctor`, `delete`, `caught`

**Why:** The new-expression calls `T::operator new`, then runs the constructor in that storage. When initialization exits through an exception, the expression calls the matching deallocation function, here `T::operator delete`, before the exception propagates. No destructor runs, because the object's lifetime never began. The leak only happens once the expression has returned a pointer that nobody owns.

### Question 2 [warmup] ([expr.delete])

What does the standard say about this program?

```cpp
int main() {
  int* p = new int[10];
  delete p;
}
```

A. Well-defined: `int` is trivially destructible, so there is no difference
B. Well-defined, but nine `int` objects leak
C. Ill-formed: the compiler must reject `delete` on an array pointer
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** Memory obtained from the array form of a new-expression must be released with `delete[]`. [expr.delete] makes the single-object form undefined when its operand came from an array new, with no exception for trivial types. It often appears to work for `int` because there is no array cookie, which is exactly why the first option is tempting. The compiler cannot reject it in general, because a pointer does not record which form produced it.

### Question 3 [warmup] ([expr.new], [new.delete.single])

What does this program print?

```cpp
#include <cstdio>
#include <new>

struct Boom { Boom() { throw 42; } };

int main() {
  try {
    Boom* p = new (std::nothrow) Boom;
    std::puts(p ? "non-null" : "null");
  } catch (int) {
    std::puts("caught");
  }
}
```

A. `null`
B. `caught`
C. Nothing; `std::terminate` is called because the nothrow form must not throw
D. `non-null`

**Answer (B):** `caught`

**Why:** `std::nothrow` selects the `operator new(std::size_t, const std::nothrow_t&)` allocation function, which reports allocation failure by returning null. It says nothing about the constructor. Allocation succeeds, the constructor throws, the storage is released through the matching deallocation function, and the `int` propagates to the handler. A null result only occurs when the allocation itself fails.

### Question 4 [tricky] ([expr.new], [basic.stc.dynamic.deallocation])

What does this program print?

```cpp
#include <cstdio>
#include <cstddef>
#include <new>

struct T {
  T() { throw 1; }
  static void* operator new(std::size_t n, int) { return ::operator new(n); }
  static void operator delete(void* p, int) { std::puts("placement delete"); ::operator delete(p); }
  static void operator delete(void* p) { std::puts("usual delete"); ::operator delete(p); }
};

int main() {
  try { new (42) T; } catch (int) {}
}
```

A. `usual delete`
B. Nothing; placement forms never free memory automatically
C. `placement delete` then `usual delete`
D. `placement delete`

**Answer (D):** `placement delete`

**Why:** For a placement allocation function, the matching deallocation function is the one with the same number of parameters whose extra parameter types match, here `operator delete(void*, int)`. The new-expression calls it, with the same placement argument, when the constructor throws. The usual `operator delete(void*)` is what a later delete-expression would use, so it is the tempting answer, but it is not a match for a placement new. If no placement delete matched, nothing would be freed.

### Question 5 [tricky] ([expr.delete])

Is the delete-expression in this program well-defined?

```cpp
struct Base { ~Base() {} };
struct Derived : Base {};

int main() {
  Base* b = new Derived;
  delete b;
}
```

A. Yes: `Derived` adds no members, so the two objects have the same size
B. Undefined behavior: `Base` has no virtual destructor
C. Yes: `Derived`'s destructor is implicit and does nothing
D. Ill-formed: deleting through a base pointer requires a virtual destructor

**Answer (B):** Undefined behavior: `Base` has no virtual destructor

**Why:** [expr.delete] requires that, when the static type of the deleted object differs from its dynamic type, the static type is a base class with a virtual destructor; otherwise the behavior is undefined. There is no exception for derived classes that add nothing, which is the intuition behind the first and third options. The rule is not a compile-time constraint, because the compiler generally cannot know the dynamic type, so the program is not ill-formed.

### Question 6 [tricky] ([expr.delete], [basic.stc.dynamic.deallocation])

In C++20 and later, what does this program print?

```cpp
#include <cstdio>
#include <new>

struct S {
  ~S() { std::puts("~S"); }
  void operator delete(S* p, std::destroying_delete_t) {
    std::puts("destroying delete");
    ::operator delete(p);
  }
};

int main() { delete new S; }
```

A. `destroying delete` only
B. `~S` then `destroying delete`
C. `destroying delete` then `~S`
D. Ill-formed: an `operator delete` must take `void*` as its first parameter

**Answer (A):** `destroying delete` only

**Why:** An `operator delete` whose second parameter is `std::destroying_delete_t` is a destroying operator delete, added in C++20. When a delete-expression selects one, it does not invoke the destructor; the function receives a pointer to a still-live object and is responsible for destroying it. This one never calls `p->~S()`, so `~S` is not printed. The usual order for an ordinary `operator delete` is the second option.

### Question 7 [standardese] ([expr.new])

In C++17 and later, what does this program print?

```cpp
#include <cstdio>
#include <cstddef>
#include <new>

struct T {
  T(int) { std::puts("ctor"); }
  static void* operator new(std::size_t n) { std::puts("new"); return ::operator new(n); }
  static void operator delete(void* p) { ::operator delete(p); }
};

int f() { std::puts("f"); return 0; }

int main() {
  T* p = new T(f());
  (void)p;
}
```

A. `f`, `new`, `ctor`
B. Either `f`, `new`, `ctor` or `new`, `f`, `ctor`; the order is unspecified
C. `new`, `f`, `ctor`
D. `new`, `ctor`, `f`

**Answer (C):** `new`, `f`, `ctor`

**Why:** Since C++17, [expr.new] says the invocation of the allocation function is sequenced before the evaluations of expressions in the new-initializer. So `operator new` runs first, then `f()`, then the constructor. The second option describes C++14 and earlier, where the order was unspecified. The last option is impossible because the constructor needs the value of `f()`. The object is deliberately never deleted; the question is only about order.

### Question 8 [standardese] ([expr.new], [replacement.functions])

In C++23, which values may this program return?

```cpp
#include <cstdlib>
#include <new>

int calls = 0;
void* operator new(std::size_t n) {
  ++calls;
  if (void* p = std::malloc(n ? n : 1)) return p;
  throw std::bad_alloc{};
}
void operator delete(void* p) noexcept { std::free(p); }
void operator delete(void* p, std::size_t) noexcept { std::free(p); }

int main() {
  int* p = new int(1);
  delete p;
  return calls;
}
```

A. Only 1, because a replaced `operator new` has observable side effects
B. Only 0, because unused allocations must be removed
C. Either 0 or 1
D. Any value; the replacement makes the program undefined

**Answer (C):** Either 0 or 1

**Why:** Since C++14, [expr.new] permits an implementation to omit a call to a replaceable global allocation function made by a new-expression and provide the storage itself. The permission does not depend on whether the function has been replaced, so the side effect of incrementing `calls` may disappear; GCC 16 and Clang 21 at `-O2` both return 0, and both return 1 without optimization. The replacement itself is valid. A direct call to `::operator new` would not be elidable.

# Smart pointers, control blocks, and allocators

> How unique_ptr achieves zero-overhead ownership, what a shared_ptr control block stores, and how allocator_traits and std::pmr decouple allocation strategy from container types.

- **Source:** C++ Atlas (https://cppatlas.com/topics/smart-pointers-and-allocators)
- **Track:** Memory model
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [unique.ptr] (https://eel.is/c++draft/unique.ptr), [util.smartptr.shared] (https://eel.is/c++draft/util.smartptr.shared), [util.smartptr.weak] (https://eel.is/c++draft/util.smartptr.weak), [util.smartptr.enab] (https://eel.is/c++draft/util.smartptr.enab), [allocator.requirements] (https://eel.is/c++draft/allocator.requirements), [allocator.traits] (https://eel.is/c++draft/allocator.traits), [mem.res] (https://eel.is/c++draft/mem.res)
- **cppreference links:** [std::unique_ptr](https://en.cppreference.com/w/cpp/memory/unique_ptr), [std::make_unique](https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique), [std::shared_ptr](https://en.cppreference.com/w/cpp/memory/shared_ptr), [std::make_shared](https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared), [std::weak_ptr](https://en.cppreference.com/w/cpp/memory/weak_ptr), [std::enable_shared_from_this](https://en.cppreference.com/w/cpp/memory/enable_shared_from_this), [std::allocator_traits](https://en.cppreference.com/w/cpp/memory/allocator_traits), [std::pmr::polymorphic_allocator](https://en.cppreference.com/w/cpp/memory/polymorphic_allocator), [std::pmr::memory_resource](https://en.cppreference.com/w/cpp/memory/memory_resource)
- **Prerequisites:** raii-and-resource-management, object-lifetime-and-storage, copy-and-move

Raw `new` and `delete` mix two distinct responsibilities: obtaining memory and tracking who destroys the object. Modern C++ splits ownership models (`std::unique_ptr`, `std::shared_ptr`, `std::weak_ptr`) from allocation strategies (`std::allocator_traits`, `std::pmr::memory_resource`), giving you deterministic teardown without hidden runtime costs.

## Exclusive ownership and deleter footprint

`std::unique_ptr<T, Deleter>` models single, non-copyable ownership. Move operations transfer the wrapped pointer and null the source in two register instructions, and the destructor invokes `Deleter` if the stored pointer is non-null. Because the deleter is a template parameter baked into the type, the compiler optimizes empty stateless deleters—such as `std::default_delete<T>`, empty function objects, or captureless lambdas—via empty-base optimization or `[[no_unique_address]]`, making `sizeof(std::unique_ptr<T>) == sizeof(T*)`.

When you pass a function pointer (`void(*)(T*)`) or a stateful capturing lambda as `Deleter`, that state lives inside the `unique_ptr` itself, doubling or growing its footprint and changing its static type. For array buffers (`std::unique_ptr<T[]>`), the specialization provides `operator[]`, omits `*` and `->`, dispatches `delete[]`, and blocks derived-to-base pointer conversions because array indexing scales by `sizeof(Base)`. Since C++20, `std::make_unique_for_overwrite<T[]>(n)` lets you allocate large uninitialized arrays without paying for a forced zero-fill.

> **Mental model.** A `unique_ptr` with a stateless deleter compiles to a single machine pointer; only its deleted copy operations and deterministic destructor distinguish it from `T*`.

```cpp
#include <cstddef>
#include <memory>

struct HandleCloser {
    void operator()(int* p) const noexcept { delete p; }
};

void close_raw(int* p) noexcept { delete p; }

static_assert(sizeof(std::unique_ptr<int>) == sizeof(int*));
static_assert(sizeof(std::unique_ptr<int, HandleCloser>) == sizeof(int*));
static_assert(sizeof(std::unique_ptr<int, void(*)(int*)>) == 2 * sizeof(int*));

auto scratch = std::make_unique_for_overwrite<std::byte[]>(4096);
```

## Shared ownership and the control block

Unlike `unique_ptr`, `std::shared_ptr<T>` is always two pointers wide (`sizeof == 2 * sizeof(void*)`): the **stored pointer** returned by `get()` and a pointer to a heap-allocated **control block**. That control block holds four ingredients: an atomic strong reference count (`use_count`), an atomic weak reference count (`weak_count`), a type-erased deleter, and a copy of the allocator used to create the control block itself.

Keeping the stored pointer separate from the control block unlocks two crucial features. First, converting `std::shared_ptr<Derived>` to `std::shared_ptr<Base>` works safely even when `Base` has a **non-virtual** destructor or uses multiple inheritance, because the control block's type-erased deleter remembers the original `Derived*` passed at construction while the stored pointer shifts to the `Base` subobject. Second, the **aliasing constructor** `std::shared_ptr<Member>(owner, &owner->member)` creates a handle pointing directly to a subobject while still keeping `owner`'s control block alive.

Prefer `std::make_shared<T>(args...)` or `std::allocate_shared<T>(alloc, args...)` whenever possible: both allocate a single contiguous block holding the control block alongside `T`'s storage, cutting allocation count in half and improving cache locality.

> **Pitfall.** Never construct two separate `shared_ptr` instances from the same raw pointer `T*`; each creates an independent control block and triggers double deletion. Notice too that `std::make_shared` fuses the control block and `T` into one allocation: although `~T()` runs immediately when the strong count drops to zero, the raw memory block cannot be freed until every surviving `weak_ptr` also expires.

```cpp
#include <memory>

struct Base { int tag = 1; }; // Intentionally non-virtual destructor
struct Derived : Base { int payload = 42; };

struct Session : std::enable_shared_from_this<Session> {
    std::shared_ptr<Session> share() { return shared_from_this(); }
};

void ownership_demo() {
    std::shared_ptr<Base> base = std::make_shared<Derived>();
    auto derived = std::make_shared<Derived>();
    // Aliasing constructor: points to member while sharing Derived's control block
    std::shared_ptr<int> alias(derived, &derived->payload);
    static_assert(sizeof(alias) == 2 * sizeof(void*));
}
```

## Weak observers and shared_from_this

`std::weak_ptr<T>` points to the control block without incrementing the strong count, breaking parent-child ownership cycles. Because another thread can drop the last `shared_ptr` immediately after `wp.expired()` returns `false`, never gate access on `expired()`. Always call `wp.lock()`, which atomically checks `use_count > 0` and increments it in one indivisible step, returning either an owning `shared_ptr<T>` or null.

Remember the thread-safety boundary of `shared_ptr`: control-block reference counts are atomic, so copying or destroying **distinct** `shared_ptr` instances sharing one control block across threads is race-free. Reading and writing the **same** `shared_ptr` object concurrently from two threads is still a data race; wrap shared handles in `std::atomic<std::shared_ptr<T>>` (C++20) rather than the deprecated `std::atomic_load` free functions.

When a managed object must hand out `shared_ptr` handles to `*this`, inherit publicly from `std::enable_shared_from_this<T>`. Its hidden `weak_this` member is populated by `shared_ptr` constructors *after* `T` finishes constructing. Calling `shared_from_this()` inside a constructor or on an object owned by the stack or `unique_ptr` throws `std::bad_weak_ptr` (well-defined since C++17).

## Allocator traits and propagation contracts

Standard containers do not invoke allocator methods directly; they talk through `std::allocator_traits<Alloc>`, which supplies defaults for `pointer`, `rebind_alloc`, `construct`, `destroy`, `max_size`, and C++23 `allocate_at_least`. `allocate_at_least(alloc, n)` returns an `allocation_result` containing `{ptr, count}`, allowing `std::vector` to adopt extra bucket capacity rounded up by slab allocators instead of wasting trailing bytes.

For stateful allocators—such as arenas or per-subsystem pools—four propagation traits govern container operations:

- **`propagate_on_container_copy_assignment` (POCCA)** decides whether `a = b` copies `b`'s allocator handle into `a`.
- **`propagate_on_container_move_assignment` (POCMA)** decides whether `a = std::move(b)` transfers `b`'s allocator handle so `a` can steal `b`'s buffer in constant time.
- **`propagate_on_container_swap` (POCS)** decides whether `swap(a, b)` exchanges allocator handles along with buffers.
- **`select_on_container_copy_construction(alloc)`** returns the allocator used by a freshly copy-constructed container.

If `POCMA` is `std::false_type` and two containers hold unequal allocators (`a.get_allocator() != b.get_allocator()`), `a = std::move(b)` **cannot** steal `b`'s heap buffer—`a`'s allocator could not legally free memory owned by `b`'s arena—so the container falls back to linear element-by-element moves into fresh allocations.

> **Standardese.** Under `[allocator.requirements]` and `[container.requirements]`, calling `swap` on two containers whose allocators compare unequal when `propagate_on_container_swap` is `std::false_type` causes **undefined behavior** rather than copying elements.

## Type-erased allocators with std::pmr

Template allocators bake allocation strategy into the container's static type: `std::vector<int, ArenaAlloc>` cannot be passed to a function expecting `std::vector<int>`. The `<memory_resource>` library erases the allocator type behind a virtual interface, `std::pmr::memory_resource` (`do_allocate`, `do_deallocate`, `do_is_equal`). Every `std::pmr::vector<int>` uses `std::pmr::polymorphic_allocator<int>`, which stores a single `memory_resource*` pointer, keeping the container's ABI uniform whether backed by a stack buffer (`monotonic_buffer_resource`), a thread-local pool (`unsynchronized_pool_resource`), or a mutex-protected pool (`synchronized_pool_resource`).

> **Pitfall.** `std::pmr::polymorphic_allocator` sets `POCCA`, `POCMA`, and `POCS` to `std::false_type`, and `select_on_container_copy_construction()` returns a handle to `std::pmr::get_default_resource()`. Move-assigning a `pmr::vector` backed by a stack arena into a `pmr::vector` bound to a different resource silently relocates elements one by one into the target's resource instead of stealing the buffer pointer.

```cpp
#include <array>
#include <cstddef>
#include <memory_resource>
#include <vector>

void pmr_arena_demo() {
    std::array<std::byte, 1024> stack_bytes{};
    std::pmr::monotonic_buffer_resource arena{
        stack_bytes.data(), stack_bytes.size(), std::pmr::null_memory_resource()
    };

    std::pmr::vector<int> local(&arena);
    local.push_back(10);
    local.push_back(20);

    std::pmr::vector<int> heap_vec; // Uses std::pmr::get_default_resource()
    heap_vec = std::move(local);    // POCMA is false: copies/moves elements, does NOT steal arena
}
```

The memory-management choices summarize cleanly across footprint, allocation count, and strategy propagation:

| Mechanism | Footprint | Heap Control Block | Type-Erased Strategy | Propagation / Safety Rule |
| --- | --- | --- | --- | --- |
| `unique_ptr<T>` | 1 pointer | None | No (deleter in type) | Move-only; stateless deleter has zero size cost |
| `shared_ptr<T>` | 2 pointers | Yes (atomic counts) | Yes (deleter + allocator) | `make_shared` fuses object and control block |
| `weak_ptr<T>` | 2 pointers | Observes control block | Yes | Always promote via `lock()`, never `expired()` |
| Custom `Allocator` | Zero or state | None | No (infects container type) | Check `POCMA` and `POCS` on stateful arenas |
| `pmr::polymorphic_allocator` | 1 pointer | None | Yes (`memory_resource*`) | Never propagates on copy, move-assign, or swap |

## What to remember

- Reach for `std::unique_ptr` by default; stateless deleters add zero size overhead over `T*`, while function-pointer deleters double the pointer size.
- A `std::shared_ptr` carries two pointers (stored pointer plus control block), making aliasing and non-virtual base destruction safe, while `make_shared` trades deferred memory release alongside `weak_ptr` for a single allocation.
- Promote `std::weak_ptr` strictly with `lock()`, and never call `shared_from_this()` inside constructors or on objects not yet adopted by a `shared_ptr`.
- Use `std::allocator_traits` in generic containers and watch `POCMA` and `POCS` whenever allocators carry state.
- `std::pmr` unifies container types across arenas and pools, but non-propagating `polymorphic_allocator` contracts turn cross-resource move assignment into element-by-element reallocation.

## Concept Map Outline

- **Smart pointers & allocators:** C++ decouples deterministic object ownership from raw memory allocation strategies.
  - **Exclusive ownership (unique_ptr):** Move-only handle encoding cleanup inside its deleter type parameter.
    - **Zero-size stateless deleter:** Default or empty functor deleters keep sizeof(unique_ptr<T>) equal to T*.
    - **Stateful or function deleters:** Function pointers or capturing lambdas grow unique_ptr beyond one pointer.
    - **Array specialization T[]:** Provides operator[], calls delete[], and blocks derived-to-base array conversion.
  - **Shared ownership (shared_ptr):** Two-pointer reference-counted handle sharing a heap control block.
    - **Two-pointer layout:** Stores both get() and control-block pointer, enabling aliasing and base casts.
    - **Control block fields:** Tracks atomic strong count, weak count, type-erased deleter, and allocator.
    - **make_shared single allocation:** Fuses T storage and control block until the last weak_ptr also expires.
  - **Weak observation & thread safety:** Non-owning observers break cycles and inspect control blocks safely.
    - **Atomic promotion via lock():** Checks and increments use_count atomically, avoiding expired() TOCTOU races.
    - **enable_shared_from_this:** Initializes weak_this after construction; throws bad_weak_ptr if unowned.
    - **atomic<shared_ptr<T>>:** C++20 wrapper required when mutating the same shared_ptr handle across threads.
  - **Allocator traits & contracts:** allocator_traits normalizes container-to-allocator interaction and propagation.
    - **Trait defaults & allocate_at_least:** Synthesizes construct/destroy and lets containers claim over-allocated buckets.
    - **POCCA, POCMA & POCS:** False POCMA forces O(N) moves across unequal arenas; unequal false POCS swap is UB.
  - **Polymorphic memory resources:** std::pmr erases allocator types behind a memory_resource* pointer.
    - **Uniform container types:** All std::pmr::vector<T> share one static type across arenas and pools.
    - **monotonic_buffer_resource:** Fast bump allocator over stack or upstream buffers freed wholesale on teardown.
    - **Non-propagating pmr handles:** polymorphic_allocator sets POCCA, POCMA, and POCS false to preserve arena identity.

## Standardese Quiz Questions

### Question 1 [warmup] ([unique.ptr.single.general])

On a 64-bit platform (8-byte pointers), what are the sizes of p1 (empty functor deleter) and p2 (function pointer deleter)?

```cpp
struct EmptyDeleter { void operator()(int* p) const noexcept { delete p; } };
void fn_deleter(int* p) noexcept { delete p; }

std::unique_ptr<int, EmptyDeleter> p1;
std::unique_ptr<int, void(*)(int*)> p2(nullptr, fn_deleter);
```

A. Both p1 and p2 are 8 bytes
B. p1 is 8 bytes and p2 is 16 bytes
C. p1 is 16 bytes and p2 is 8 bytes
D. Both p1 and p2 are 16 bytes

**Answer (B):** p1 is 8 bytes and p2 is 16 bytes

**Why:** std::unique_ptr compresses an empty stateless functor deleter (like EmptyDeleter or std::default_delete) to zero extra bytes via empty-base optimization or [[no_unique_address]], so p1 stays 8 bytes. A function pointer void(*)(int*) carries runtime address state stored inside p2, doubling its size to 16 bytes.

### Question 2 [warmup] ([util.smartptr.weak.obs])

Two threads share access to an object observed through std::weak_ptr<Session> wp. What is the correct way to safely use the Session if it is still alive?

A. Call if (auto sp = wp.lock()) { sp->ping(); }
B. Call if (!wp.expired()) { wp.lock()->ping(); }
C. Cast wp with std::static_pointer_cast<Session>
D. Read wp.use_count() > 0 before calling wp.lock()

**Answer (A):** Call if (auto sp = wp.lock()) { sp->ping(); }

**Why:** Checking expired() or use_count() before locking creates a time-of-check-to-time-of-use race: another thread can destroy the final shared_ptr in between, causing wp.lock() to return null. Calling wp.lock() directly atomically checks and increments the strong reference count.

### Question 3 [tricky] ([util.smartptr.shared.create])

A BigBuffer object is created via std::make_shared<BigBuffer>(), a std::weak_ptr<BigBuffer> observer is saved, and all std::shared_ptr handles are then destroyed while observer stays alive. What happens to BigBuffer's destructor and its heap memory?

```cpp
auto sp = std::make_shared<BigBuffer>();
std::weak_ptr<BigBuffer> observer = sp;
sp.reset();
// observer is still alive here
```

A. Neither ~BigBuffer() runs nor is any memory freed until observer is destroyed
B. Both ~BigBuffer() runs and the entire heap allocation is freed immediately on sp.reset()
C. ~BigBuffer() runs immediately on sp.reset(), but the underlying memory block stays allocated until observer expires
D. observer.lock() reconstructs BigBuffer on demand from the control block

**Answer (C):** ~BigBuffer() runs immediately on sp.reset(), but the underlying memory block stays allocated until observer expires

**Why:** std::make_shared allocates the control block and BigBuffer in a single contiguous heap allocation. When the strong count hits zero, ~BigBuffer() is invoked immediately, yet the combined memory chunk cannot be passed to deallocate until weak_count also reaches zero.

### Question 4 [tricky] ([mem.poly.allocator.class], [container.alloc.reqmts])

In the snippet below, src allocates from a stack monotonic_buffer_resource, whereas dst uses std::pmr::get_default_resource(). What happens during dst = std::move(src);?

```cpp
std::array<std::byte, 512> buf{};
std::pmr::monotonic_buffer_resource arena{buf.data(), buf.size()};
std::pmr::vector<int> src(&arena);
src.assign({1, 2, 3, 4});

std::pmr::vector<int> dst; // default memory resource
dst = std::move(src);
```

A. dst steals src's buffer pointer in O(1) time and adopts arena as its allocator
B. Compilation fails because pmr::vector objects with different resources have incompatible types
C. Undefined behavior because arena and the default resource compare unequal
D. dst retains the default memory resource and moves/copies the elements into newly allocated storage because polymorphic_allocator's POCMA is false_type

**Answer (D):** dst retains the default memory resource and moves/copies the elements into newly allocated storage because polymorphic_allocator's POCMA is false_type

**Why:** std::pmr::polymorphic_allocator defines propagate_on_container_move_assignment as std::false_type. Because dst.get_allocator() != src.get_allocator(), move assignment cannot transfer ownership of src's arena buffer and instead moves elements individually into memory allocated by dst's resource.

### Question 5 [standardese] ([util.smartptr.shared.const], [expr.delete])

Base has a non-virtual destructor and Derived publicly inherits from Base. Compare destroying sp (std::shared_ptr<Base>) vs destroying up (std::unique_ptr<Base>) when both were initialized from new Derived.

```cpp
struct Base { int a = 1; }; // non-virtual ~Base()
struct Derived : Base { std::string s = "data"; };

std::shared_ptr<Base> sp(new Derived);
std::unique_ptr<Base> up(new Derived);
```

A. Both invoke undefined behavior when destroyed because Base lacks a virtual destructor
B. sp cleanly invokes ~Derived() via its control block's type-erased deleter, whereas up invokes undefined behavior (delete on Base* with non-virtual destructor)
C. up cleanly invokes ~Derived() via default_delete, whereas sp leaks s
D. Both safely invoke ~Derived() in C++20 and later

**Answer (B):** sp cleanly invokes ~Derived() via its control block's type-erased deleter, whereas up invokes undefined behavior (delete on Base* with non-virtual destructor)

**Why:** std::shared_ptr<Base>(new Derived) captures the static type Derived* inside its control block's type-erased deleter at construction time, so teardown deletes the complete Derived object safely. By contrast, std::unique_ptr<Base> stores only std::default_delete<Base>, calling delete static_cast<Base*>(p), which is undefined behavior under [expr.delete] when ~Base() is non-virtual.

### Question 6 [standardese] ([util.smartptr.enab])

A class Node publicly inherits from std::enable_shared_from_this<Node>. In C++17 and later, what happens if Node::Node() calls shared_from_this() inside its constructor body?

```cpp
struct Node : std::enable_shared_from_this<Node> {
    Node() { auto self = shared_from_this(); }
};
auto p = std::make_shared<Node>();
```

A. Returns a valid std::shared_ptr<Node> sharing the incoming make_shared control block
B. Silent undefined behavior with a null control block
C. Throws std::bad_weak_ptr because weak_this is not initialized until after Node construction finishes
D. Fails to compile unless Node is created via std::shared_ptr<Node>(new Node)

**Answer (C):** Throws std::bad_weak_ptr because weak_this is not initialized until after Node construction finishes

**Why:** The std::shared_ptr constructor populates enable_shared_from_this's internal weak_this member only after the managed Node object has finished constructing. Under C++17+ [util.smartptr.enab], shared_from_this() is specified as return shared_ptr<T>(weak_this), which throws std::bad_weak_ptr when weak_this is empty.

# Smart pointers

> unique_ptr makes single ownership a property of the type at no run-time cost, shared_ptr counts owners in a separate control block, and weak_ptr observes without owning. This page covers what each one stores, where the deleter lives, which operations are thread-safe, and the bugs that come from owning one object twice.

- **Source:** C++ Atlas (https://cppatlas.com/topics/smart-pointers)
- **Track:** Memory model
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [unique.ptr] (https://eel.is/c++draft/unique.ptr), [unique.ptr.dltr] (https://eel.is/c++draft/unique.ptr.dltr), [util.smartptr.shared] (https://eel.is/c++draft/util.smartptr.shared), [util.smartptr.shared.const] (https://eel.is/c++draft/util.smartptr.shared.const), [util.smartptr.shared.create] (https://eel.is/c++draft/util.smartptr.shared.create), [util.smartptr.weak] (https://eel.is/c++draft/util.smartptr.weak), [util.smartptr.enab] (https://eel.is/c++draft/util.smartptr.enab), [util.smartptr.atomic] (https://eel.is/c++draft/util.smartptr.atomic), [smartptr.adapt] (https://eel.is/c++draft/smartptr.adapt)
- **cppreference links:** [std::unique_ptr](https://en.cppreference.com/w/cpp/memory/unique_ptr), [std::shared_ptr](https://en.cppreference.com/w/cpp/memory/shared_ptr), [std::shared_ptr constructors](https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr), [std::make_shared, std::make_shared_for_overwrite](https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared), [std::weak_ptr](https://en.cppreference.com/w/cpp/memory/weak_ptr), [std::enable_shared_from_this](https://en.cppreference.com/w/cpp/memory/enable_shared_from_this), [std::out_ptr_t](https://en.cppreference.com/w/cpp/memory/out_ptr_t)
- **Prerequisites:** raii-and-resource-management, copy-and-move, dynamic-allocation-new-and-delete

## The one idea

A smart pointer is a class that owns an object and releases it in its destructor. The three standard ones differ in where the knowledge of ownership lives. For `std::unique_ptr<T, D>` it lives in the type: there is exactly one owner, the deleter is a template argument, and the object is a pointer plus whatever state the deleter needs. For `std::shared_ptr<T>` it lives in a separate heap object, the **control block**, which counts owners and remembers how to destroy the object. `std::weak_ptr<T>` points at the same control block without contributing to the owner count.

> **Mental model.** A `unique_ptr` is a raw pointer with a destructor and a deleted copy constructor. A `shared_ptr` is two raw pointers: one to the object you dereference, and one to a control block that decides when, and how, something gets destroyed. Those two pointers need not agree, and most of the surprises come from that.

The general case for tying resources to scopes is the topic on RAII; this page is about the specific tools.

## unique_ptr: ownership in the type

`unique_ptr` is move-only. Moving transfers the pointer and leaves the source null, which the standard guarantees, unlike moved-from states in general. The deleter is part of the type, so `unique_ptr<FILE, int(*)(FILE*)>` and `unique_ptr<FILE, Closer>` are different types.

The deleter is stored inside the `unique_ptr`. An empty class deleter, such as the default `std::default_delete<T>` or a captureless lambda, costs nothing in practice, because libstdc++, libc++ and MSVC all use the empty base optimization or `[[no_unique_address]]`. The standard does not promise a size. A function pointer deleter, by contrast, must be stored, so it makes the object two pointers wide on every mainstream ABI.

```cpp
#include <cstdio>
#include <memory>

struct Closer { void operator()(std::FILE* f) const { std::fclose(f); } };

using File  = std::unique_ptr<std::FILE, Closer>;               // stateless deleter
using FileP = std::unique_ptr<std::FILE, int (*)(std::FILE*)>;  // stores a function pointer

static_assert(sizeof(File) == sizeof(std::FILE*));     // holds on libstdc++ and libc++, not guaranteed
static_assert(sizeof(FileP) == 2 * sizeof(std::FILE*));  // the function pointer is stored
```

`unique_ptr<T[]>` is a separate partial specialization. Its default deleter calls `delete[]`, it provides `operator[]` instead of `operator*` and `operator->`, and it refuses conversions from pointers to derived types, because deleting an array through a base pointer is undefined. `std::make_unique<T[]>(n)` value-initializes the elements; C++20's `std::make_unique_for_overwrite` default-initializes them, which skips zeroing for trivial types.

### Incomplete types and the out-of-line destructor

`unique_ptr<T>` may be declared with an incomplete `T`, which is what makes it the standard pimpl member. But `default_delete<T>::operator()` requires a complete type, and the implicitly defined destructor of the enclosing class calls it wherever that destructor is defined. If the class's destructor is implicit, it is defined inline in every translation unit that destroys one, where `Impl` is incomplete, and the program is ill-formed.

```cpp
#include <memory>

// widget.h
struct Impl;
struct Widget {
  Widget();
  ~Widget();                 // declared here, defined where Impl is complete
  std::unique_ptr<Impl> p;
};

// widget.cpp
struct Impl { int x = 0; };
Widget::Widget() : p(std::make_unique<Impl>()) {}
Widget::~Widget() = default;  // default_delete<Impl> is instantiated here
```

The same applies to a move assignment operator, which also destroys the old `Impl`. `shared_ptr` has no such requirement, because its constructor captures the deleter into the control block while the type is complete.

## shared_ptr: the control block

The control block holds the strong count (the number of `shared_ptr` owners), the weak count, the deleter and the allocator. When the strong count reaches zero, the object is destroyed by the stored deleter. When the weak count also reaches zero, the control block itself is freed.

Because the deleter is type-erased in the control block, two `shared_ptr<T>` with different deleters have the same type. A less obvious consequence is that the deleter is chosen from the pointer type you passed to the constructor, not from `T`. A `shared_ptr<Base>` built from `new Derived` deletes a `Derived*`, so it calls the correct destructor even when `Base` has no virtual destructor. A `shared_ptr<void>` destroys its object correctly for the same reason.

```cpp
#include <cstdio>
#include <memory>

struct Base    { ~Base()    { std::puts("~Base"); } };     // not virtual
struct Derived : Base { ~Derived() { std::puts("~Derived"); } };

int main() {
  std::shared_ptr<Base> p(new Derived);
  p.reset();                         // prints ~Derived, ~Base
  // std::unique_ptr<Base> u(new Derived); would be undefined when u is destroyed,
  // because default_delete<Base> runs delete on a Base*
}
```

### make_shared trade-offs

`std::make_shared<T>(args...)` is recommended to perform a single allocation holding both the control block and the object. That halves the allocations and improves locality, and it was also the fix for exception-unsafe argument lists before C++17. The costs are real, though.

- The object's storage is part of the control block, so it cannot be returned until the last `weak_ptr` is gone, even though the object is destroyed when the last `shared_ptr` goes. A large object observed by a long-lived `weak_ptr` keeps its memory.
- You cannot supply a custom deleter.
- The constructor must be accessible from inside the library, so a class with a private constructor and a static factory cannot use it directly.
- It initializes with parentheses. Since C++20, parenthesized aggregate initialization makes aggregates work too.

C++20 added `make_shared<T[]>` for arrays and `make_shared_for_overwrite`. `std::allocate_shared` takes an allocator for the combined block.

### The aliasing constructor

`shared_ptr<T>(const shared_ptr<U>& owner, T* p)` shares `owner`'s control block but stores `p`. The result keeps the whole owner alive while pointing into it, which is how you hand out a `shared_ptr` to a member.

```cpp
#include <cstdio>
#include <memory>
#include <utility>

int main() {
  auto owner = std::make_shared<std::pair<int, int>>(1, 2);
  std::shared_ptr<int> second(owner, &owner->second);
  owner.reset();
  std::printf("%d %ld\n", *second, second.use_count());   // prints 2 1
}
```

Nothing checks that `p` lies inside the owned object. Aliasing an empty `shared_ptr` with a non-null `p` even yields a pointer that dereferences fine and has a `use_count()` of zero.

## Thread safety: the count, not the pointee

The control block's counts are updated atomically, so different `shared_ptr` objects that share ownership may be copied, assigned and destroyed concurrently in different threads. The standard words this narrowly: for data-race purposes, the member functions access only the `shared_ptr` and `weak_ptr` objects themselves, not the objects they point to.

That leaves two things unprotected. The pointee is an ordinary object, so concurrent unsynchronized writes to `*p` race. And a single `shared_ptr` object is an ordinary object too: one thread assigning to `g` while another copies `g` is a data race on `g`, even though the counts are atomic.

> **Pitfall.** "shared_ptr is thread-safe" is true of the reference count and false of everything else. Sharing one global `shared_ptr` that some thread reassigns needs a mutex or `std::atomic<std::shared_ptr<T>>`. The atomic specialization arrived in C++20 and deprecated the old `std::atomic_load` free functions, which C++26 removes. The topic on atomics and memory ordering covers the orderings.

## weak_ptr, cycles and enable_shared_from_this

Two objects that hold `shared_ptr`s to each other never reach a strong count of zero, so neither is destroyed. Break the cycle by making the back edge, typically child to parent or observer to subject, a `weak_ptr`. To use it, call `lock()`, which atomically returns either an owning `shared_ptr` or an empty one. `expired()` is only a hint in multithreaded code, since the answer can change before you act on it.

An object that wants a `shared_ptr` to itself cannot write `std::shared_ptr<T>(this)`, because that creates a second control block. Instead it derives publicly from `std::enable_shared_from_this<T>`, which holds a `weak_ptr` that the first owning `shared_ptr` constructor fills in. `shared_from_this()` locks it.

```cpp
#include <cstdio>
#include <memory>

struct Node : std::enable_shared_from_this<Node> {};

int main() {
  auto owned = std::make_shared<Node>();
  auto again = owned->shared_from_this();      // shares owned's control block
  Node stack_node;
  try { stack_node.shared_from_this(); }
  catch (const std::bad_weak_ptr&) { std::puts("bad_weak_ptr"); }   // since C++17
}
```

Before C++17 calling `shared_from_this()` on an object that no `shared_ptr` owned was undefined; since C++17 it throws `std::bad_weak_ptr`. It also fails inside the constructor, because no `shared_ptr` owns the object yet. C++17 added `weak_from_this()`, which returns an empty `weak_ptr` in that case instead of throwing.

## Smart pointers in interfaces

The signature should say what the function does with ownership.

| Parameter | Meaning |
|---|---|
| `T&` or `T*` | uses the object, no ownership involved; `T*` if it may be null |
| `std::unique_ptr<T>` by value | takes ownership; the caller must `std::move` |
| `std::unique_ptr<T>&` | may reseat the caller's pointer |
| `std::shared_ptr<T>` by value | keeps a share; move it into storage |
| `const std::shared_ptr<T>&` | might keep a share, decided inside |

Passing `shared_ptr` by value to a function that only reads the object costs two atomic operations for nothing. Returning a `unique_ptr` from a factory is the most flexible choice, because it converts implicitly to `shared_ptr`.

C++23 added `std::out_ptr` and `std::inout_ptr` for C APIs that return a resource through a `T**` parameter. `std::out_ptr(p)` resets `p` when the adapter is constructed, passes the address of a temporary pointer, and calls `p.reset(new_value)` when the adapter is destroyed at the end of the full-expression. `std::inout_ptr(p)` instead releases `p` without deleting, passing the old value in so the API can free or reallocate it. With a `shared_ptr`, `out_ptr` requires an explicit deleter argument, and `inout_ptr` is not allowed at all, because a `shared_ptr` cannot release ownership.

```cpp
#include <cstdlib>
#include <memory>

extern "C" int c_make(int** out);   // allocates *out with malloc

struct Free { void operator()(int* p) const { std::free(p); } };

void use() {
  std::unique_ptr<int, Free> p;
  c_make(std::out_ptr(p));          // p owns the result after this full-expression
}
```

## Owning one object twice

Almost every smart-pointer crash is two owners that do not know about each other.

- Constructing two `shared_ptr`s from the same raw pointer creates two control blocks, and each deletes the object.
- `std::shared_ptr<T>(this)` inside a member function does the same thing whenever the object is already owned.
- Wrapping `p.get()` in a new smart pointer double-deletes.
- A `unique_ptr` or `shared_ptr` to an object with automatic or static storage duration deletes something `new` never made.

> **Standardese.** [util.smartptr.shared.const] says that constructing a `shared_ptr` from a raw pointer `p` produces an object that owns `p` with `use_count() == 1`. Nothing in that specification consults any other `shared_ptr`, so two constructions from the same pointer give two owners that each believe they are alone, and [util.smartptr.shared.dest] then has each of them delete `p`. The second deletion is undefined.

The fixes are mechanical: create objects with `make_unique` or `make_shared` so a raw owning pointer never exists, pass `shared_ptr` copies rather than raw pointers when ownership must be shared, and use `enable_shared_from_this` for self-references.

## What to remember

- `unique_ptr` is move-only, a moved-from one is null, and its deleter is part of the type; empty deleters cost no space in practice, but the standard promises no size.
- `unique_ptr<T[]>` calls `delete[]`, has `operator[]`, and refuses derived-to-base conversions.
- A pimpl `unique_ptr<Impl>` needs the enclosing class's destructor, and move assignment, defined where `Impl` is complete.
- `shared_ptr` keeps the deleter in the control block, chosen from the constructor's pointer type, so `shared_ptr<Base>(new Derived)` destroys correctly without a virtual destructor.
- `make_shared` makes one allocation, but the object's memory outlives it until the last `weak_ptr` is gone.
- The aliasing constructor shares ownership with one object while pointing at another.
- Counts are atomic; the pointee and a single shared `shared_ptr` object are not. Use `std::atomic<std::shared_ptr<T>>` (C++20) for the latter.
- Break cycles with `weak_ptr` and `lock()`. `shared_from_this()` on an unowned object throws `bad_weak_ptr` since C++17.
- `out_ptr` and `inout_ptr` (C++23) adapt smart pointers to `T**` C APIs and update the pointer at the end of the full-expression.
- Never create a second owner from a raw pointer that already has one.

## Concept Map Outline

- **Smart pointers:** unique_ptr owns alone, shared_ptr counts owners in a control block, weak_ptr observes.
  - **unique_ptr:** Move-only single owner; the deleter is part of the type.
    - **Moved-from is null:** The standard guarantees a moved-from unique_ptr holds nullptr.
    - **Deleter size:** Empty deleters cost nothing in practice; a function pointer deleter is stored. No size is guaranteed.
    - **unique_ptr<T[]>:** Calls delete[], offers operator[], and rejects derived-to-base conversions.
    - **Pimpl destructor:** Declare ~Widget in the header and define it where Impl is complete.
  - **shared_ptr:** An object pointer plus a control block pointer; the two need not agree.
    - **Control block:** Holds strong count, weak count, deleter and allocator.
    - **Deleter from ctor type:** shared_ptr<Base>(new Derived) deletes a Derived*, even without a virtual destructor.
    - **make_shared:** One allocation; the object's memory stays until the last weak_ptr is gone.
    - **Aliasing constructor:** Shares one object's ownership while pointing at another, such as a member.
  - **Thread safety:** Only the reference counts are synchronized.
    - **Distinct copies:** Different shared_ptr objects sharing a block may be used concurrently.
    - **One shared object:** Reading and assigning the same shared_ptr from two threads is a data race.
    - **atomic<shared_ptr> (C++20):** Replaces the deprecated atomic_load free functions, removed in C++26.
  - **weak_ptr:** Points at the control block without keeping the object alive.
    - **Breaking cycles:** Make back edges weak so strong counts can reach zero.
    - **lock():** Atomically yields an owner or an empty shared_ptr; expired() is only a hint.
    - **shared_from_this:** Needs an existing owner; throws bad_weak_ptr since C++17, UB before.
    - **weak_from_this (C++17):** Returns an empty weak_ptr instead of throwing when unowned.
  - **Interfaces:** The parameter type states what happens to ownership.
    - **T& or T*:** Use without ownership; prefer these when the callee only reads or writes the object.
    - **unique_ptr by value:** A sink: the callee takes ownership and the caller must move.
    - **out_ptr (C++23):** Resets at construction, stores the T** result at the end of the full-expression.
    - **inout_ptr (C++23):** Releases the old pointer into the call; not usable with shared_ptr.
  - **Double ownership:** Two owners that do not know about each other delete twice.
    - **Two from one raw:** Each shared_ptr built from the same raw pointer makes its own control block.
    - **shared_ptr(this):** Creates a second control block; use enable_shared_from_this.
    - **Wrapping get():** A new owner of p.get() deletes what p will delete again.

## Standardese Quiz Questions

### Question 1 [warmup] ([unique.ptr.single])

Is this program well-formed?

```cpp
#include <memory>

int main() {
  auto a = std::make_unique<int>(1);
  auto b = a;
  (void)b;
}
```

A. Well-formed: `b` shares ownership with `a`
B. Well-formed: `a` is moved into `b` and left null
C. Ill-formed: the copy constructor of `std::unique_ptr` is deleted
D. Undefined behavior: the `int` is deleted twice

**Answer (C):** Ill-formed: the copy constructor of `std::unique_ptr` is deleted

**Why:** `a` is an lvalue, so `auto b = a;` selects the copy constructor, which `std::unique_ptr` declares as deleted. Ownership only moves when you ask for it with `std::move(a)`, after which `a` is guaranteed to be null. The second option describes the removed `std::auto_ptr`, whose copy constructor silently transferred ownership.

### Question 2 [warmup] ([util.smartptr.weak.obs], [util.smartptr.shared.obs])

What does this program print?

```cpp
#include <cstdio>
#include <memory>

int main() {
  auto p = std::make_shared<int>(1);
  auto q = p;
  std::weak_ptr<int> w = p;
  p.reset();
  std::printf("%ld %ld %d\n", q.use_count(), w.use_count(), w.expired());
}
```

A. `1 0 0`
B. `2 1 0`
C. `1 1 1`
D. `1 1 0`

**Answer (D):** `1 1 0`

**Why:** After `p.reset()`, `q` is the only owner, so the strong count is 1. `weak_ptr::use_count()` reports the number of `shared_ptr` owners of the shared object, not the number of weak references, so it is also 1. Since an owner remains, `expired()` is false. Reading `w.use_count()` as the weak count is the usual mistake behind the first option.

### Question 3 [warmup] ([util.smartptr.enab], [util.smartptr.shared.const])

In C++17 and later, what does this program print?

```cpp
#include <cstdio>
#include <memory>

struct Node : std::enable_shared_from_this<Node> {};

int main() {
  Node n;
  try {
    auto p = n.shared_from_this();
    std::puts(p ? "owner" : "empty");
  } catch (const std::bad_weak_ptr&) {
    std::puts("bad_weak_ptr");
  }
}
```

A. `bad_weak_ptr`
B. `empty`
C. `owner`
D. Nothing predictable: the behavior is undefined

**Answer (A):** `bad_weak_ptr`

**Why:** `shared_from_this()` locks the `weak_ptr` stored in the `enable_shared_from_this` base. No `shared_ptr` ever owned `n`, so that `weak_ptr` is empty, and since C++17 the call is specified as `shared_ptr<T>(weak_this)`, whose constructor throws `std::bad_weak_ptr`. Before C++17 the call had a precondition that an owner existed, so the last option was correct in C++14. Use `weak_from_this()` if an empty result is preferable to an exception.

### Question 4 [tricky] ([util.smartptr.shared.const], [util.smartptr.shared.dest], [expr.delete])

`Base` has no virtual destructor. What does this program print?

```cpp
#include <cstdio>
#include <memory>

struct Base { ~Base() { std::puts("~Base"); } };
struct Derived : Base { ~Derived() { std::puts("~Derived"); } };

int main() {
  std::shared_ptr<Base> p(new Derived);
  p.reset();
}
```

A. `~Base` only, because the destructor is not virtual
B. `~Derived` then `~Base`
C. Nothing predictable: deleting through a base without a virtual destructor is undefined
D. Ill-formed: `shared_ptr<Base>` cannot be constructed from `Derived*`

**Answer (B):** `~Derived` then `~Base`

**Why:** The constructor `template<class Y> shared_ptr(Y* p)` records a deleter that performs `delete p` on the `Y*` it received, here `Derived*`. The control block keeps that deleter, so the eventual deletion has static type `Derived` and runs both destructors in the right order. With `std::unique_ptr<Base>` the default deleter is `default_delete<Base>`, and the third option would be correct.

### Question 5 [tricky] ([unique.ptr.dltr.dflt], [unique.ptr.single.dtor])

This is the whole translation unit; `Impl` is defined in another one. Is it well-formed?

```cpp
#include <memory>

struct Impl;

struct Widget {
  std::unique_ptr<Impl> p;
};

int main() { Widget w; }
```

A. Well-formed: `unique_ptr` is designed to hold incomplete types
B. Well-formed, but the `Impl` destructor is not called
C. Undefined behavior: deleting an incomplete type skips the destructor
D. Ill-formed: destroying `w` instantiates `default_delete<Impl>::operator()` with `Impl` incomplete

**Answer (D):** Ill-formed: destroying `w` instantiates `default_delete<Impl>::operator()` with `Impl` incomplete

**Why:** Declaring a `unique_ptr<Impl>` member with `Impl` incomplete is fine, which is why the first option is tempting. But `Widget`'s implicit destructor is defined in this translation unit, it calls `~unique_ptr`, and that calls `default_delete<Impl>::operator()`, which requires a complete type; both libstdc++ and libc++ reject it. A raw `delete` of an incomplete type would be the undefined case in the third option, and `default_delete` exists precisely to turn that into a compile error. Declare `~Widget()` here and define it as `= default` where `Impl` is complete.

### Question 6 [tricky] ([util.smartptr.shared.const])

What does this program print?

```cpp
#include <cstdio>
#include <memory>
#include <utility>

int main() {
  auto owner = std::make_shared<std::pair<int, int>>(1, 2);
  std::shared_ptr<int> second(owner, &owner->second);
  owner.reset();
  std::printf("%d %ld\n", *second, second.use_count());
}
```

A. `2 1`
B. `2 2`
C. Nothing predictable: `second` dangles once `owner` is reset
D. `2 0`

**Answer (A):** `2 1`

**Why:** The aliasing constructor makes `second` share ownership with `owner`, using the same control block, while storing a pointer to the `second` member. Resetting `owner` drops one of the two owners, so the pair stays alive and `use_count()` is 1. The dangling answer assumes `second` owns only an `int`, which it does not; a use count of 0 only happens when the aliasing source was empty.

### Question 7 [standardese] ([util.smartptr.shared], [intro.races], [res.on.data.races])

What does the standard say about this program?

```cpp
#include <memory>
#include <thread>

std::shared_ptr<int> g = std::make_shared<int>(0);

void reader() { std::shared_ptr<int> local = g; (void)local; }
void writer() { g = std::make_shared<int>(1); }

int main() {
  std::thread a(reader), b(writer);
  a.join();
  b.join();
}
```

A. Well-defined: reference count updates are atomic
B. Well-defined only where atomic operations on two pointers are lock-free
C. Data race on the `int` objects, but not on `g`
D. Data race on `g`: undefined behavior

**Answer (D):** Data race on `g`: undefined behavior

**Why:** [util.smartptr.shared] says that, for determining data races, `shared_ptr` member functions access and modify only the `shared_ptr` and `weak_ptr` objects themselves. Copying `g` reads `g`, and assigning to `g` modifies it, from two threads without synchronization, so the program has a data race on the single object `g`. The atomic count only makes it safe for different `shared_ptr` objects that share a control block to be used concurrently. Use a mutex or `std::atomic<std::shared_ptr<int>>`.

### Question 8 [standardese] ([out.ptr.t], [out.ptr])

In C++23, what does this program print, one token per line?

```cpp
#include <cstdio>
#include <cstdlib>
#include <memory>

int c_make(int** out) {
  std::puts("c_make");
  *out = static_cast<int*>(std::malloc(sizeof(int)));
  **out = 7;
  return 0;
}

struct Free {
  void operator()(int* p) const { std::puts("free"); std::free(p); }
};

int main() {
  std::unique_ptr<int, Free> p(static_cast<int*>(std::malloc(sizeof(int))));
  c_make(std::out_ptr(p));
  std::printf("%d\n", *p);
}
```

A. `c_make`, `free`, `7`, `free`
B. `c_make`, `7`, `free`, because the original allocation leaks
C. `free`, `c_make`, `7`, `free`
D. Ill-formed: `std::out_ptr` requires an empty smart pointer

**Answer (C):** `free`, `c_make`, `7`, `free`

**Why:** The `out_ptr_t` constructor calls `p.reset()` immediately, so the original allocation is freed before `c_make` runs. The function writes into the adapter's own pointer, and the adapter's destructor, at the end of the full-expression, calls `p.reset(new_value)`, which has nothing old left to free. The final `free` comes from `p`'s destructor. The first option is what you would see if the reset happened only in the destructor. `inout_ptr` differs again: it releases the old pointer without freeing it and passes it in, expecting the function to free or reuse it.

# Allocators and polymorphic memory resources

> An allocator tells a container where its memory comes from, and allocator_traits fills in everything the allocator leaves out. This page covers the minimal allocator, rebinding, the propagation traits that decide what copy, move and swap do with allocator state, and the std::pmr design that puts the memory source behind a virtual interface.

- **Source:** C++ Atlas (https://cppatlas.com/topics/allocators-and-pmr)
- **Track:** Memory model
- **Estimated reading time:** 15 minutes
- **ISO C++ clauses:** [allocator.requirements] (https://eel.is/c++draft/allocator.requirements), [allocator.traits] (https://eel.is/c++draft/allocator.traits), [default.allocator] (https://eel.is/c++draft/default.allocator), [container.reqmts] (https://eel.is/c++draft/container.reqmts), [container.alloc.reqmts] (https://eel.is/c++draft/container.alloc.reqmts), [mem.res] (https://eel.is/c++draft/mem.res), [mem.poly.allocator.class] (https://eel.is/c++draft/mem.poly.allocator.class), [mem.res.pool] (https://eel.is/c++draft/mem.res.pool), [mem.res.monotonic.buffer] (https://eel.is/c++draft/mem.res.monotonic.buffer), [allocator.uses] (https://eel.is/c++draft/allocator.uses), [allocator.adaptor] (https://eel.is/c++draft/allocator.adaptor)
- **cppreference links:** [Allocator named requirement](https://en.cppreference.com/w/cpp/named_req/Allocator), [std::allocator_traits](https://en.cppreference.com/w/cpp/memory/allocator_traits), [std::pmr::memory_resource](https://en.cppreference.com/w/cpp/memory/memory_resource), [std::pmr::polymorphic_allocator](https://en.cppreference.com/w/cpp/memory/polymorphic_allocator), [std::pmr::monotonic_buffer_resource](https://en.cppreference.com/w/cpp/memory/monotonic_buffer_resource), [std::pmr::unsynchronized_pool_resource](https://en.cppreference.com/w/cpp/memory/unsynchronized_pool_resource), [std::scoped_allocator_adaptor](https://en.cppreference.com/w/cpp/memory/scoped_allocator_adaptor), [std::allocator_traits::allocate_at_least](https://en.cppreference.com/w/cpp/memory/allocator_traits/allocate_at_least)
- **Prerequisites:** dynamic-allocation-new-and-delete, copy-and-move, sequence-containers

## The one idea

An allocator is a small value that a container stores and asks for memory. It is not the memory itself, and it is not a heap; it is a handle to one. Two allocators compare equal when memory obtained from one can be released through the other. Everything interesting about allocators follows from that: a container may only hand its buffer to another container whose allocator could free it.

The container never calls the allocator directly. It goes through `std::allocator_traits<A>`, which supplies a default for almost every member, so a usable allocator needs only a handful of declarations.

> **Mental model.** Think of an allocator as a library card. Containers with equal cards can trade books freely. Containers with different cards must copy the books, because each library only takes back its own. The propagation traits answer one question: when a container is copied, moved or swapped, does its card go with the books?

## The minimal allocator and allocator_traits

The Allocator requirements in [allocator.requirements] are written as a long table, but almost every row has a default in `allocator_traits`. What you must write is `value_type`, `allocate`, `deallocate`, equality, and a converting constructor from the same template with another element type.

```cpp
#include <cstddef>
#include <list>
#include <new>
#include <vector>

template <class T>
struct Mini {
  using value_type = T;
  Mini() = default;
  template <class U> Mini(const Mini<U>&) noexcept {}
  T* allocate(std::size_t n) { return static_cast<T*>(::operator new(n * sizeof(T))); }
  void deallocate(T* p, std::size_t n) noexcept { ::operator delete(p, n * sizeof(T)); }
};
template <class T, class U>
bool operator==(const Mini<T>&, const Mini<U>&) { return true; }

std::vector<int, Mini<int>> v{1, 2, 3};
std::list<int, Mini<int>> l{1, 2, 3};   // rebinds Mini<int> to Mini<node>
```

Since C++20 `operator!=` is synthesized from `operator==`. `allocator_traits` provides `pointer` as `value_type*`, `size_type`, `max_size`, `construct` through `std::construct_at`, `destroy` through `std::destroy_at`, the propagation traits as `false_type`, and `is_always_equal` as `std::is_empty<A>`. A stateless allocator is therefore treated as always equal without saying so.

`std::allocator<T>` is the default. C++20 removed its `construct`, `destroy` and `rebind` members, which `allocator_traits` provides anyway, and made it usable in constant evaluation.

### Rebinding

A `std::list<int, A>` never allocates an `int`. It allocates nodes that contain an `int` and two pointers. It obtains an allocator for nodes with `allocator_traits<A>::rebind_alloc<Node>`, which defaults to replacing the first template argument, so `Mini<int>` becomes `Mini<Node>`. Then it constructs that allocator from the one you passed, which is why the converting constructor is required.

Rebinding must preserve identity. An allocator and its rebound copy must compare equal both ways, meaning memory from either can be freed by the other. A stateful allocator therefore carries the same state, typically a pointer to an arena, through every rebind.

## Stateful allocators and the propagation traits

When allocators carry state, unequal allocators can coexist, and each container operation has to decide what to do with them. Three traits make the decision, plus one function for copies.

| Operation | Trait or function | If it says no and the allocators differ |
|---|---|---|
| copy construction | `select_on_container_copy_construction()` | the returned allocator is used, whatever it is |
| copy assignment | `propagate_on_container_copy_assignment` (POCCA) | keep the target's allocator, copy elements into its memory |
| move assignment | `propagate_on_container_move_assignment` (POCMA) | keep the target's allocator, move elements one by one |
| swap | `propagate_on_container_swap` (POCS) | undefined behavior |

Move construction has no trait. It always move-constructs the allocator from the source, so the new container can adopt the source's buffer in constant time.

The move-assignment case explains a surprise in the standard containers' signatures. When POCMA is true, the target frees its own memory with its old allocator, takes the source's allocator, and steals the buffer. When POCMA is false but the allocators compare equal, it can steal the buffer anyway. When POCMA is false and they compare unequal, the target's allocator cannot free the source's buffer, so the target must allocate its own memory and move-assign or move-construct each element. That can throw. So `vector`'s move assignment is declared `noexcept(POCMA || is_always_equal)`, and for allocators that are neither, it is not `noexcept`.

```cpp
#include <memory_resource>
#include <type_traits>
#include <vector>

static_assert(std::is_nothrow_move_assignable_v<std::vector<int>>);
static_assert(!std::is_nothrow_move_assignable_v<std::pmr::vector<int>>);
static_assert(std::is_nothrow_move_constructible_v<std::pmr::vector<int>>);
```

> **Standardese.** [container.reqmts] says that when POCS is false, `swap` does not exchange the allocators, and the behavior is undefined unless the two allocators compare equal. Swap is specified as constant time and non-throwing for containers other than `std::array`, so it cannot fall back to copying elements the way move assignment does.

`std::allocator` has POCMA true and is always equal, which is why ordinary containers never meet these cases.

## std::pmr: the resource behind a pointer

C++17's `std::pmr` moves the memory source out of the allocator's type and behind a virtual interface. `std::pmr::memory_resource` has public non-virtual `allocate`, `deallocate` and `is_equal`, which call the private virtual `do_allocate`, `do_deallocate` and `do_is_equal`. `std::pmr::polymorphic_allocator<T>` is a thin allocator that stores a `memory_resource*` and forwards to it. Containers in `std::pmr`, such as `std::pmr::vector<T>`, are aliases for the ordinary templates with that allocator, so containers using different resources have the same type.

The surprising part is that `polymorphic_allocator` never propagates. All three propagation traits are false, and `select_on_container_copy_construction` returns a default-constructed allocator, which uses the current default resource rather than the source's resource.

```cpp
#include <memory_resource>
#include <vector>

void copy_does_not_follow() {
  std::pmr::monotonic_buffer_resource arena;
  std::pmr::vector<int> a({1, 2, 3}, &arena);
  std::pmr::vector<int> b = a;
  // b.get_allocator().resource() == std::pmr::get_default_resource(), not &arena
}
```

The design reflects how resources are used. A resource is usually scoped: a monotonic arena on the stack for one request, a pool for one subsystem. An object's resource is decided when the object is constructed and then never changes. If copying or assigning propagated the resource, a long-lived container could silently start pointing at an arena about to be destroyed. The cost is that `b = std::move(a)` between different resources copies element by element and may throw.

> **Pitfall.** Returning a `std::pmr::vector` by value from a function, or copying one into a member, does not keep the arena it was built in. The copy goes to the default resource, which is usually `new_delete_resource()`. Pass the resource explicitly, as in `std::pmr::vector<int> b(a, &arena);`.

## The standard resources

The library provides two global resources and three classes.

- `std::pmr::new_delete_resource()` allocates with `::operator new` and is the initial default resource.
- `std::pmr::null_memory_resource()` throws `std::bad_alloc` from every allocation. As an upstream it turns "fell back to the heap" into an error.
- `std::pmr::monotonic_buffer_resource` hands out memory by bumping a pointer through an optional initial buffer, then through blocks of growing size obtained from its upstream. `deallocate` does nothing; everything is returned at once by `release()` or the destructor. It is not thread-safe.
- `std::pmr::unsynchronized_pool_resource` and `std::pmr::synchronized_pool_resource` keep pools of fixed-size blocks for a range of sizes and route larger requests to the upstream. The synchronized one may be used from several threads. `std::pmr::pool_options` tunes the largest pooled size and the chunk size.

`std::pmr::set_default_resource` changes what default-constructed polymorphic allocators use, for the whole program.

```cpp
#include <cstddef>
#include <memory_resource>
#include <vector>

int sum_small() {
  std::byte buf[1024];
  std::pmr::monotonic_buffer_resource arena(buf, sizeof buf, std::pmr::null_memory_resource());
  std::pmr::vector<int> v(&arena);
  for (int i = 0; i < 10; ++i) v.push_back(i);   // no heap; overflowing buf throws bad_alloc
  int s = 0;
  for (int x : v) s += x;
  return s;
}
```

## Uses-allocator construction and scoped_allocator_adaptor

A container of strings has two levels of allocation: the outer buffer and each string's characters. Uses-allocator construction is the protocol that passes the outer allocator down. A type opts in through `std::uses_allocator<T, Alloc>`, normally by having a nested `allocator_type`, and accepts the allocator either as a trailing constructor argument or after a leading `std::allocator_arg` tag. C++20 exposed the protocol through `std::uses_allocator_construction_args` and `std::make_obj_using_allocator`, and extended it to `std::pair` members.

`polymorphic_allocator::construct` always performs uses-allocator construction, so the elements of a `std::pmr::vector<std::pmr::string>` use the vector's resource with no further work.

```cpp
#include <memory_resource>
#include <string>
#include <vector>

bool nested_uses_arena() {
  std::pmr::monotonic_buffer_resource arena;
  std::pmr::vector<std::pmr::string> v(&arena);
  v.emplace_back("a string long enough to defeat the small buffer");
  return v[0].get_allocator().resource() == &arena;   // true
}
```

For allocators that do not do this themselves, C++11's `std::scoped_allocator_adaptor<Outer, Inner...>` wraps the outer allocator and performs uses-allocator construction of each element with the inner allocator. It predates `std::pmr` and is mostly seen in code that uses custom arena allocators without virtual dispatch.

## allocate_at_least (C++23)

Real allocators round requests up to a size class, so asking for 13 elements might return room for 16. C++23 lets the container learn that. `std::allocator_traits<A>::allocate_at_least(a, n)` returns a `std::allocation_result` holding `ptr` and `count`, with `count >= n`. It calls the allocator's own `allocate_at_least` if it has one, and otherwise returns `{a.allocate(n), n}`. `std::allocator` provides the member.

The obligation runs the other way on deallocation: pass `deallocate` a size between the requested `n` and the returned `count`, normally `count` itself. A `vector` that records the returned count as its capacity can absorb the extra slack before reallocating. Whether a given library uses it inside its containers is an implementation choice, and the standard resources do not offer it.

## What to remember

- Equal allocators can free each other's memory; that one rule decides when buffers may change hands.
- A minimal allocator needs `value_type`, `allocate`, `deallocate`, `==` and a converting constructor; `allocator_traits` supplies the rest.
- Node-based containers rebind the allocator to their node type, and rebound copies must compare equal.
- POCCA, POCMA and POCS decide whether the allocator follows the elements. Move construction always takes the source's allocator.
- Move assignment with unequal, non-propagating allocators moves element by element and may throw, so such containers are not nothrow move assignable.
- Swapping containers with unequal, non-propagating allocators is undefined.
- `polymorphic_allocator` never propagates, and copy construction uses the default resource, not the source's.
- `monotonic_buffer_resource` never frees until release; pool resources reuse blocks by size; `null_memory_resource` makes overflow an error.
- `polymorphic_allocator` performs uses-allocator construction, so nested pmr containers share the outer resource; `scoped_allocator_adaptor` does the same for other allocators.
- `allocate_at_least` (C++23) reports the real size of an allocation through `allocator_traits`.

## Concept Map Outline

- **Allocators and pmr:** An allocator is a handle to a memory source; equal handles can free each other's memory.
  - **Allocator model:** Containers reach allocators only through allocator_traits.
    - **Minimal allocator:** value_type, allocate, deallocate, == and a converting constructor are enough.
    - **Traits defaults:** construct, destroy, pointer, max_size and is_always_equal = is_empty come from traits.
    - **Rebind:** Node containers allocate nodes through rebind_alloc; rebound copies must compare equal.
  - **Propagation traits:** Decide whether the allocator follows the elements on copy, move and swap.
    - **Copy construction:** Uses select_on_container_copy_construction of the source's allocator.
    - **POCMA false, unequal:** Move assignment allocates and moves elements one by one, so it may throw.
    - **POCS false, unequal:** swap is undefined behavior; there is no element-wise fallback.
    - **Move construction:** Always moves the allocator and adopts the buffer; it is noexcept.
  - **polymorphic_allocator:** Stores a memory_resource* and forwards to its virtual interface.
    - **memory_resource:** Public allocate, deallocate, is_equal call private virtual do_ functions.
    - **Never propagates:** POCCA, POCMA and POCS are all false, so a container keeps its resource.
    - **Copies use default:** Copy construction picks get_default_resource(), not the source's resource.
    - **Not nothrow move-assign:** pmr::vector move assignment is noexcept(false) because resources may differ.
  - **Standard resources:** Two global resources and three resource classes ship with the library.
    - **new_delete_resource:** Uses ::operator new; it is the initial default resource.
    - **null_memory_resource:** Throws bad_alloc on every allocation; an upstream that forbids fallback.
    - **monotonic_buffer_resource:** Bump allocation; deallocate is a no-op until release() or destruction.
    - **Pool resources:** Reuse fixed-size blocks; the synchronized version is thread-safe.
  - **Uses-allocator construction:** Passes the container's allocator down to elements that accept one.
    - **Opting in:** uses_allocator, via nested allocator_type, plus a trailing or allocator_arg-led parameter.
    - **pmr does it:** polymorphic_allocator::construct makes nested pmr strings share the outer resource.
    - **scoped_allocator_adaptor:** C++11 adaptor that performs the same protocol for other allocators.
  - **allocate_at_least:** C++23: allocator_traits returns {ptr, count} with count >= n.
    - **Fallback:** Without a member, traits return {allocate(n), n}.
    - **Deallocate size:** Pass a size between the requested n and the returned count.

## Standardese Quiz Questions

### Question 1 [warmup] ([allocator.requirements], [allocator.traits])

In C++23, is this program well-formed?

```cpp
#include <cstddef>
#include <list>
#include <new>

template <class T>
struct Mini {
  using value_type = T;
  Mini() = default;
  template <class U> Mini(const Mini<U>&) noexcept {}
  T* allocate(std::size_t n) { return static_cast<T*>(::operator new(n * sizeof(T))); }
  void deallocate(T* p, std::size_t n) noexcept { ::operator delete(p, n * sizeof(T)); }
};
template <class T, class U>
bool operator==(const Mini<T>&, const Mini<U>&) { return true; }

int main() {
  std::list<int, Mini<int>> l{1, 2, 3};
  return static_cast<int>(l.size()) - 3;
}
```

A. Ill-formed: `Mini` has no `construct` or `destroy` members
B. Ill-formed: `std::list` needs a nested `rebind` template to allocate nodes
C. Ill-formed: `operator!=` is missing
D. Well-formed

**Answer (D):** Well-formed

**Why:** Containers use allocators only through `std::allocator_traits`, which supplies `construct` and `destroy` through `std::construct_at` and `std::destroy_at`, and a default `rebind_alloc` that replaces the first template argument, turning `Mini<int>` into `Mini<Node>`. The converting constructor is what lets the list build that rebound allocator. Since C++20, `a != b` is rewritten to `!(a == b)`, so no separate `operator!=` is needed.

### Question 2 [warmup] ([mem.res.monotonic.buffer.mem])

What does the standard guarantee about `same`?

```cpp
#include <memory_resource>

int main() {
  std::pmr::monotonic_buffer_resource mr;
  void* p = mr.allocate(64);
  mr.deallocate(p, 64);
  void* q = mr.allocate(64);
  bool same = (p == q);
  return same;
}
```

A. `same` is false: `deallocate` does nothing, so the block is not reused before `release()`
B. `same` is true: the freed block is the best fit for the next request
C. It is unspecified
D. Undefined behavior: a monotonic resource does not support `deallocate`

**Answer (A):** `same` is false: `deallocate` does nothing, so the block is not reused before `release()`

**Why:** `monotonic_buffer_resource::do_deallocate` has no effect; memory goes back only when `release()` is called or the resource is destroyed. The next allocation is carved from unused space, so it cannot overlap the first block, which is still allocated as far as the resource is concerned. Calling `deallocate` is valid, it is just a no-op, which is what makes this resource so fast. Reuse of freed blocks is what the pool resources do.

### Question 3 [warmup] ([mem.res.global])

What does this program print?

```cpp
#include <cstdio>
#include <memory_resource>
#include <new>

int main() {
  try {
    void* p = std::pmr::null_memory_resource()->allocate(1);
    std::puts(p ? "allocated" : "null");
  } catch (const std::bad_alloc&) {
    std::puts("bad_alloc");
  }
}
```

A. `null`
B. `allocated`, because the request falls back to the default resource
C. `bad_alloc`
D. Nothing predictable: the behavior is undefined

**Answer (C):** `bad_alloc`

**Why:** Every call to `allocate` on `null_memory_resource()` throws `std::bad_alloc`; it never returns null, because `memory_resource::allocate` reports failure only by exception. There is no fallback, which is the point: as the upstream of a monotonic or pool resource, it turns "ran out of the local buffer" into an error instead of a silent heap allocation.

### Question 4 [tricky] ([mem.poly.allocator.mem], [container.alloc.reqmts])

What does this program print?

```cpp
#include <cstdio>
#include <memory_resource>
#include <vector>

int main() {
  std::pmr::monotonic_buffer_resource arena;
  std::pmr::vector<int> a({1, 2, 3}, &arena);
  std::pmr::vector<int> b = a;
  std::printf("%d %d\n", b.get_allocator().resource() == &arena,
              b.get_allocator().resource() == std::pmr::get_default_resource());
}
```

A. `1 0`
B. `0 1`
C. `1 1`
D. `0 0`

**Answer (B):** `0 1`

**Why:** Copy construction asks `select_on_container_copy_construction()` for the new container's allocator, and `polymorphic_allocator` returns a default-constructed allocator, which uses `get_default_resource()`. So the copy does not follow the source into `arena`. The first answer is what you get with an allocator that copies its state, and it is the usual expectation; `std::pmr` deliberately avoids it so that copies never outlive a scoped resource.

### Question 5 [tricky] ([container.alloc.reqmts], [mem.poly.allocator.class])

What does this program print?

```cpp
#include <cstdio>
#include <memory_resource>
#include <utility>
#include <vector>

int main() {
  std::pmr::monotonic_buffer_resource r1, r2;
  std::pmr::vector<int> a({1, 2, 3}, &r1);
  std::pmr::vector<int> b(&r2);
  const int* old = a.data();
  b = std::move(a);
  std::printf("%d %d %zu\n", b.get_allocator().resource() == &r2,
              b.data() == old, b.size());
}
```

A. `0 1 3`: `b` takes `a`'s allocator and buffer
B. `1 1 3`
C. `1 0 0`
D. `1 0 3`

**Answer (D):** `1 0 3`

**Why:** `polymorphic_allocator` does not propagate on move assignment, and the two allocators compare unequal because their resources differ. `b` keeps its allocator, and since that allocator cannot free memory from `r1`, `b` cannot adopt `a`'s buffer; it allocates from `r2` and moves the elements individually. The first option is what `std::vector<int>` with `std::allocator` does, where move assignment is a pointer steal. The container requirements still guarantee `b` ends up with `a`'s former value.

### Question 6 [tricky] ([mem.poly.allocator.mem], [allocator.uses.construction])

What does this program print?

```cpp
#include <cstdio>
#include <memory_resource>
#include <string>
#include <vector>

int main() {
  std::pmr::monotonic_buffer_resource arena;
  std::pmr::vector<std::pmr::string> v(&arena);
  v.emplace_back("a string long enough to defeat the small buffer");
  std::printf("%d\n", v[0].get_allocator().resource() == &arena);
}
```

A. `0`, because the string was constructed from `const char*` with no allocator
B. `1`
C. `0`, because `polymorphic_allocator` does not propagate
D. It depends on whether the string fits in the small buffer

**Answer (B):** `1`

**Why:** `polymorphic_allocator::construct` performs uses-allocator construction. `std::pmr::string` uses a `polymorphic_allocator<char>`, so the vector's allocator is appended to the constructor arguments and the string's characters come from `arena`. Non-propagation is about copy, move and swap of the container, not about constructing its elements, which is why the third option is wrong. A string's allocator is set at construction regardless of its length.

### Question 7 [standardese] ([vector.overview], [container.alloc.reqmts])

With a conforming C++23 standard library, which of these assertions fails?

```cpp
#include <memory_resource>
#include <type_traits>
#include <vector>

static_assert(std::is_nothrow_move_constructible_v<std::pmr::vector<int>>);  // A
static_assert(std::is_nothrow_move_assignable_v<std::vector<int>>);           // B
static_assert(std::is_nothrow_move_assignable_v<std::pmr::vector<int>>);      // C
```

A. A
B. B
C. C
D. None of them

**Answer (C):** C

**Why:** `vector`'s move assignment is declared `noexcept(propagate_on_container_move_assignment::value || is_always_equal::value)`. For `std::allocator` POCMA is true, so B holds. For `polymorphic_allocator` both are false, because move assignment between unequal resources must allocate and move elements one by one, which can throw; so C fails. Move construction is unconditionally `noexcept`, because it always moves the allocator along with the buffer, so A holds. The failing `static_assert` makes this translation unit ill-formed, which is an easy way to check the answer.

### Question 8 [standardese] ([container.reqmts], [container.alloc.reqmts])

What does the standard say about this program?

```cpp
#include <memory_resource>
#include <vector>

int main() {
  std::pmr::monotonic_buffer_resource r1, r2;
  std::pmr::vector<int> a({1, 2}, &r1);
  std::pmr::vector<int> b({3}, &r2);
  a.swap(b);
}
```

A. Well-defined: the elements are swapped one by one, as move assignment would do
B. Well-defined: the buffers and the resources are exchanged
C. Ill-formed: `polymorphic_allocator` is not swappable
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** The container requirements say that when `propagate_on_container_swap` is false, the allocators are not swapped, and the behavior is undefined unless the two allocators compare equal. Here they use different resources, so they are unequal. Unlike move assignment, swap has no element-wise fallback, because it is required to run in constant time without moving individual elements. The second option is what happens when POCS is true.

# Pointers, arrays and pointer arithmetic

> A pointer value is not just an address; it points to an object, past the end of one, nowhere, or it is invalid. This page covers array-to-pointer decay and where it stops, what arithmetic and comparison the standard defines, multidimensional arrays, function pointers, nullptr, references and std::to_address.

- **Source:** C++ Atlas (https://cppatlas.com/topics/pointers-arrays-and-pointer-arithmetic)
- **Track:** Memory model
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [basic.compound] (https://eel.is/c++draft/basic.compound), [basic.stc.general] (https://eel.is/c++draft/basic.stc.general), [conv.array] (https://eel.is/c++draft/conv.array), [dcl.fct] (https://eel.is/c++draft/dcl.fct), [expr.add] (https://eel.is/c++draft/expr.add), [expr.rel] (https://eel.is/c++draft/expr.rel), [expr.eq] (https://eel.is/c++draft/expr.eq), [comparisons.general] (https://eel.is/c++draft/comparisons.general), [basic.fundamental] (https://eel.is/c++draft/basic.fundamental), [dcl.ref] (https://eel.is/c++draft/dcl.ref), [pointer.conversion] (https://eel.is/c++draft/pointer.conversion)
- **cppreference links:** [Pointer declaration](https://en.cppreference.com/w/cpp/language/pointer), [Array declaration](https://en.cppreference.com/w/cpp/language/array), [Additive operators](https://en.cppreference.com/w/cpp/language/operator_arithmetic), [Comparison operators](https://en.cppreference.com/w/cpp/language/operator_comparison), [std::less](https://en.cppreference.com/w/cpp/utility/functional/less), [std::nullptr_t](https://en.cppreference.com/w/cpp/types/nullptr_t), [std::to_address](https://en.cppreference.com/w/cpp/memory/to_address)
- **Prerequisites:** object-lifetime-and-storage, strict-aliasing-and-undefined-behavior

## The one idea

The hardware sees an address. The abstract machine sees a pointer value, and [basic.compound] says every value of an object pointer type is exactly one of four things: a pointer to an object, a pointer past the end of an object, the null pointer value, or an invalid pointer value. Arithmetic, comparison and dereference are all defined in terms of which of the four you hold and which object it relates to, never in terms of the bits.

> **Mental model.** A pointer is an address plus a claim about which object it belongs to. The address says where; the claim says what you may do. Two pointers can hold the same address and still have different values, because one points to an object and the other points past the end of its neighbour.

The topic on strict aliasing introduces this idea, which is often called provenance, and the type-access rules that go with it. This page works through the rest of the pointer model.

## Four kinds of pointer value

A pointer past the end of an object represents the first byte after it. You may form it, copy it, compare it and subtract it, but you may not dereference it. Every object counts as an array of one element for this purpose, so `&x + 1` is a valid past-the-end pointer even for a scalar.

A pointer becomes invalid when the storage it points into reaches the end of its duration: after `delete`, after the block holding an automatic variable exits, after `free`. Dereferencing an invalid pointer, or passing it to a deallocation function, is undefined. Every other use, including copying it, comparing it, or printing it, is implementation-defined, because some architectures trap when an invalid address is merely loaded into a register.

```cpp
int* dangling() {
  int* p = new int(1);
  delete p;          // p now holds an invalid pointer value
  int* q = p;        // implementation-defined, not undefined
  return q;          // *q, or delete q, would be undefined
}
```

Equality between a past-the-end pointer and a pointer to some unrelated object is a trap of its own. If `a` and `b` happen to be adjacent, `a + 1` and `&b` may have the same address. [expr.eq] makes the result of `a + 1 == &b` unspecified in that case, which lets an optimizer fold it to `false` in one place and compute `true` in another; GCC has been observed doing exactly that.

## Array-to-pointer decay and where it stops

An lvalue or rvalue of type "array of N `T`" converts to a prvalue `T*` pointing to the first element. This conversion happens in almost every expression, which is why arrays look like pointers. It does not happen in these places:

- the operand of `sizeof`, `decltype`, `typeid` and unary `&`;
- binding a reference to the array, including deducing `T` for a `const T&` parameter;
- initializing a `char` array from a string literal;
- the range of a range-based `for`, and a structured binding declaration;
- a lambda capture by copy, which copies the whole array.

The most surprising rule runs the other way. A function parameter declared as an array is adjusted to a pointer, so `void f(int a[10])` declares `void f(int* a)`, and the `10` is ignored.

```cpp
#include <type_traits>

int a[4];
static_assert(std::is_same_v<decltype(a), int[4]>);       // no decay in decltype
static_assert(std::is_same_v<decltype(&a), int(*)[4]>);   // pointer to the whole array
static_assert(std::is_same_v<decltype(+a), int*>);        // unary + forces decay

void f(int p[10]) {
  static_assert(std::is_same_v<decltype(p), int*>);       // the parameter is a pointer
}

template <class T> constexpr bool by_value(T)      { return std::is_array_v<T>; }
template <class T> constexpr bool by_ref(const T&) { return std::is_array_v<T>; }
static_assert(!by_value(a) && by_ref(a));                 // T is int* vs int[4]
```

`&a` and `a` usually hold the same address but have different types, so `&a + 1` steps over the whole array while `a + 1` steps over one `int`.

## Arithmetic stays inside one array

[expr.add] defines `P + J` only when `P` points to element `i` of an array of `n` elements and `0 <= i + J <= n`. Anything else is undefined, whether or not the result is dereferenced. Subtraction `P - Q` is defined only when both point into, or one past the end of, the same array, and gives `i - j` as a `std::ptrdiff_t`.

`std::ptrdiff_t` is a signed type, and `std::size_t` can describe larger objects than it can measure. If an array of `char` is longer than `PTRDIFF_MAX` bytes, subtracting pointers at its two ends gives a difference that is not representable, and the behavior is undefined. On 64-bit systems no allocation is that large in practice. On 32-bit systems a buffer of more than 2 GB is conceivable, which is one reason GCC refuses to declare an object larger than `PTRDIFF_MAX` and glibc's `malloc` refuses such requests.

### Multidimensional arrays

`int m[3][4]` is an array of three arrays of four `int`. It decays to `int (*)[4]`, and `m[i]` is itself an array that decays to `int*`. The twelve `int` objects are contiguous, but they are not one array of twelve. A pointer obtained from `m[0]` belongs to a four-element array, so `&m[0][0] + 4` is its past-the-end pointer, and `(&m[0][0])[5]` is out of bounds even though `m[1][1]` lives at that address.

```cpp
constexpr int flat() {
  int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
  int* p = &m[0][0];
  return p[3];   // undefined: p points into m[0], which has three elements
}
// constexpr int v = flat();   // rejected by GCC 16 and Clang 21 as not a constant expression
```

Code that walks a matrix with a single `int*` is common and works on every mainstream compiler, but the standard does not bless it. `std::mdspan` in C++23, covered in the topic on span and mdspan, is the sanctioned way to view one flat buffer as several dimensions.

> **Pitfall.** Treating an object as bytes and stepping through it with `unsigned char*` is universally relied on, for example in `memcpy` implementations and hashing, but the C++23 wording does not clearly define pointer arithmetic over an object's representation. The proposal P1839 addresses that gap. Prefer `std::memcpy`, `std::bit_cast` or `std::as_bytes` where you can.

## Comparing pointers

Equality with `==` and `!=` works for any two pointers of compatible type, with the past-the-end caveat already described. Relational comparison with `<` and friends is specified only within one object: later array elements compare greater, and later-declared non-static data members compare greater provided neither is a zero-size subobject. Before C++23 that member rule also required the members to have the same access; P1847 dropped the condition. For pointers to unrelated objects the result is unspecified, not undefined, which differs from C, where such a comparison is undefined.

```cpp
struct P { int a; int b; };

constexpr bool members_ordered() {
  P p{};
  return &p.a < &p.b;            // guaranteed true: b is declared later
}
static_assert(members_ordered());

bool unrelated(int& x, int& y) {
  return &x < &y;                // unspecified result, and never a constant expression
}
```

`std::less<T*>`, `std::ranges::less` and the other comparison function objects are guaranteed to yield an implementation-defined strict total order over pointers, consistent with the built-in operators wherever those are specified. That is why `std::set<T*>` and `std::map<T*, V>` work. The guarantee does not make the result usable in constant evaluation for unrelated pointers; both GCC 16 and Clang 21 reject that.

> **Standardese.** [expr.rel] says that when two pointers do not point into the same array or into the same object, neither is required to compare greater than the other, and [comparisons.general] separately requires `std::less` and its relatives to produce an implementation-defined strict total order consistent with the built-in operators.

## Pointer-interconvertibility, function pointers and nullptr

Two objects are pointer-interconvertible when a `reinterpret_cast` between pointers to them yields a pointer to the other object: a standard-layout class object and its first non-static data member, a union and its members, and an object and itself. The strict-aliasing topic explains why other casts only relabel the pointer. C++20 added `std::is_pointer_interconvertible_with_class(&S::m)` to test the member case; GCC 16 supports it and libc++ in LLVM 21 does not yet.

A function name decays to a pointer to function, and a function pointer cannot take part in arithmetic. Function pointers may be converted to other function pointer types with `reinterpret_cast`, and converting back yields the original, but calling through the wrong type is undefined. Converting a function pointer to `void*` is conditionally-supported; POSIX requires it, which is how `dlsym` works.

`nullptr` is a prvalue of type `std::nullptr_t`, which is neither a pointer type nor an integer type. It converts to every pointer and pointer-to-member type, but not to `int`. It converts to `bool` only in direct-initialization, as in `bool b(nullptr);`, and `bool b = nullptr;` is ill-formed. `NULL` is an implementation-defined null pointer constant, often `0` or `0L`, so `g(NULL)` may pick the integer overload or be ambiguous; `nullptr` always selects the pointer overload.

```cpp
#include <cstddef>

void g(int);
void g(char*);

void call() {
  g(nullptr);    // g(char*)
  g(0);          // g(int)
}

static_assert(sizeof(std::nullptr_t) == sizeof(void*));   // guaranteed by [basic.fundamental]
```

## References, and std::to_address

A reference is an alias, not an object. It has no address of its own, `sizeof` on a reference type yields the size of the referenced type, and [dcl.ref] leaves it unspecified whether a reference requires storage at all. Implementations represent a reference member or parameter as a pointer when they need storage, and a local reference to a known object usually needs none. A reference cannot be null in a valid program: forming one from a null pointer is already undefined. It also cannot be reseated, which is why a reference member makes a class's implicit copy assignment operator deleted.

C++20's `std::to_address(p)` returns a raw pointer equal to what `p` points to, without dereferencing. For a raw pointer it returns `p`. For a fancy pointer or a contiguous iterator it uses `std::pointer_traits<P>::to_address` if provided, and otherwise calls `p.operator->()` and recurses. The practical use is getting a raw pointer from an end iterator, where `&*it` would dereference a past-the-end iterator.

```cpp
#include <memory>
#include <vector>

int* end_pointer(std::vector<int>& v) {
  return std::to_address(v.end());   // OK; &*v.end() would be undefined
}
```

## What to remember

- A pointer value points to an object, points past the end of one, is null, or is invalid. Equal addresses do not imply equal values.
- Dereferencing or deleting an invalid pointer is undefined; any other use of it, even copying, is implementation-defined.
- `p + 1 == &other` with `p` past the end is unspecified.
- Arrays decay almost everywhere, except under `sizeof`, `decltype`, unary `&`, reference binding and a few initializations. Array parameters are really pointers.
- Arithmetic is defined only within one array plus one past the end; `ptrdiff_t` overflow in subtraction is undefined.
- `int m[3][4]` is three arrays of four, not one of twelve; indexing past a row is undefined. Use `std::mdspan`.
- `<` on unrelated pointers is unspecified in C++ (undefined in C); `std::less` gives a total order.
- Function pointers do no arithmetic, and calling through a mismatched type is undefined.
- `nullptr` converts to pointers but not integers, and to `bool` only by direct-initialization; `sizeof(std::nullptr_t) == sizeof(void*)`.
- References are not objects and may not occupy storage; `std::to_address` (C++20) gets a raw pointer without dereferencing.

## Concept Map Outline

- **Pointers and arrays:** A pointer value is an address plus a claim about which object it belongs to.
  - **Pointer values:** Every object pointer value is one of exactly four kinds.
    - **Past-the-end:** May be formed, copied, compared and subtracted, never dereferenced.
    - **Invalid:** After storage ends; dereference or delete is UB, any other use is implementation-defined.
    - **Same address, different value:** p + 1 == &neighbour is unspecified.
  - **Decay:** Arrays convert to a pointer to their first element in most expressions.
    - **No decay:** Under sizeof, decltype, typeid, unary &, reference binding and range-for.
    - **Array parameters:** void f(int a[10]) declares f(int*); the bound is ignored.
    - **Deduction:** By-value T deduces int*; const T& deduces int[N].
    - **&a vs a:** &a is int(*)[N]; &a + 1 steps over the whole array.
  - **Arithmetic:** Defined only within one array, counting one past the end.
    - **Out of range:** Forming a pointer outside [0, n] is UB even without a dereference.
    - **ptrdiff_t overflow:** Subtracting across a char array longer than PTRDIFF_MAX is UB.
    - **Multidimensional:** int m[3][4] is three arrays of four; indexing past a row is UB.
    - **Byte walking:** Stepping through object bytes is relied on but under-specified; P1839 addresses it.
  - **Comparison:** == works everywhere; < is only specified within one object.
    - **Unrelated with <:** Unspecified in C++, undefined in C, never a constant expression.
    - **Member order:** Later-declared members compare greater; C++23 dropped the same-access condition.
    - **std::less:** Guarantees an implementation-defined strict total order over pointers.
  - **Other pointer kinds:** Function pointers, nullptr_t and interconvertible objects follow their own rules.
    - **Interconvertible:** Standard-layout object and first member, or union and member; other casts only relabel the pointer.
    - **Function pointers:** No arithmetic; calling through a mismatched type is UB; to void* is conditional.
    - **std::nullptr_t:** Converts to pointers, not integers; to bool only by direct-initialization.
  - **References and to_address:** Aliases without object identity, and raw pointers without dereferencing.
    - **References:** Not objects; may need no storage; never null or reseated in valid code.
    - **std::to_address:** C++20: raw pointer from a fancy pointer or iterator, safe for end().

## Standardese Quiz Questions

### Question 1 [warmup] ([conv.array], [expr.unary.op])

What is the type of `p`?

```cpp
int a[4] = {};
auto p = &a;
```

A. `int*`
B. `int**`
C. `int (*)[4]`
D. `int (&)[4]`

**Answer (C):** `int (*)[4]`

**Why:** Array-to-pointer conversion is not applied to the operand of unary `&`, so `&a` takes the address of the whole array and has type pointer to array of four `int`. It usually holds the same address as `a` after decay, which is why `int*` is tempting, but `p + 1` steps over all four elements. `int**` would need an object of type `int*` to point to, and there is none.

### Question 2 [warmup] ([conv.ptr], [basic.fundamental], [over.ics.rank])

What does this program print?

```cpp
#include <cstdio>

void f(int) { std::puts("int"); }
void f(char*) { std::puts("char*"); }

int main() {
  f(nullptr);
  f(0);
}
```

A. `char*` then `int`
B. `int` then `int`
C. Ill-formed: `f(nullptr)` is ambiguous
D. `int` then `char*`

**Answer (A):** `char*` then `int`

**Why:** `nullptr` has type `std::nullptr_t`, which converts to any pointer type but not to `int`, so only `f(char*)` is viable. The literal `0` is an exact match for `f(int)`, while converting it to `char*` would be a null pointer conversion, which ranks lower. That asymmetry is why `nullptr` replaced `0` and `NULL` for null pointers.

### Question 3 [warmup] ([dcl.fct], [expr.sizeof])

What does this program print?

```cpp
#include <cstdio>

void f(int a[10]) {
  std::printf("%d\n", sizeof(a) == sizeof(int*));
}

int main() {
  int x[10] = {};
  f(x);
}
```

A. `0`, because `a` has type `int[10]`
B. `1`
C. Ill-formed: `sizeof` cannot be applied to an array parameter
D. It depends on the platform

**Answer (B):** `1`

**Why:** A parameter declared with an array type is adjusted to the corresponding pointer type, so `a` has type `int*` and the bound `10` is ignored. `sizeof(a)` is therefore exactly `sizeof(int*)` on every implementation, and compilers warn about it with `-Wsizeof-array-argument`. To keep the bound, take the array by reference, `int (&a)[10]`, or use `std::span`.

### Question 4 [tricky] ([expr.add], [dcl.array])

What does the standard say about `p[3]`?

```cpp
int read() {
  int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
  int* p = &m[0][0];
  return p[3];
}
```

A. It reads `m[1][0]` and returns 4, because rows are contiguous
B. Implementation-defined
C. Unspecified: it returns 4 or an indeterminate value
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** `p` points to the first element of `m[0]`, which is an array of three `int`. [expr.add] defines `p + 3` as the past-the-end pointer of that array, and dereferencing a past-the-end pointer is undefined, even though `m[1][0]` occupies that address. The contiguity in the first option is real, which is why the code usually appears to work, but contiguity does not make two arrays into one. Both GCC 16 and Clang 21 reject this function in a constant expression.

### Question 5 [tricky] ([temp.deduct.call], [conv.array])

What does this program print?

```cpp
#include <cstdio>
#include <type_traits>

template <class T> bool by_value(T) { return std::is_array_v<T>; }
template <class T> bool by_ref(const T&) { return std::is_array_v<T>; }

int main() {
  int a[3] = {1, 2, 3};
  std::printf("%d%d\n", by_value(a), by_ref(a));
}
```

A. `11`
B. `00`
C. `01`
D. `10`

**Answer (C):** `01`

**Why:** When the parameter is not a reference, template argument deduction applies the array-to-pointer conversion to the argument type, so `T` is `int*`. When the parameter is a reference, no decay happens and `T` is deduced as `int[3]`, binding `const int (&)[3]`. That is how `std::size` and `std::begin` recover an array's bound.

### Question 6 [tricky] ([expr.rel], [comparisons.general])

In C++23, what does the standard say about the value `cmp()` returns?

```cpp
bool cmp() {
  int a = 0, b = 0;
  return &a < &b;
}
```

A. Undefined behavior, as in C
B. It is `true`, because `a` is declared first
C. Unspecified
D. Implementation-defined, and documented by the compiler

**Answer (C):** Unspecified

**Why:** `a` and `b` are separate complete objects, not elements of one array or members of one object, so [expr.rel] requires neither pointer to compare greater than the other. The result is unspecified: the program is valid, but it may be `true` or `false`, and the implementation need not document which. In C the same comparison is undefined, which is the tempting first answer. Declaration order only orders members of the same class object; for an order over arbitrary pointers use `std::less<int*>`.

### Question 7 [standardese] ([basic.stc.general], [basic.compound])

In C++23, what does the standard say about the line that initializes `q`?

```cpp
int main() {
  int* p = new int(1);
  delete p;
  int* q = p;
  (void)q;
}
```

A. Well-defined: only dereferencing a dangling pointer is restricted
B. Implementation-defined behavior
C. Undefined behavior
D. Unspecified behavior

**Answer (B):** Implementation-defined behavior

**Why:** After `delete p`, the value of `p` is an invalid pointer value, because the storage it pointed to has reached the end of its duration. [basic.stc.general] makes indirection through an invalid pointer and passing it to a deallocation function undefined, and every other use, including copying it, implementation-defined. The rule exists because some architectures can trap when an invalid address is loaded. Copying was undefined until CWG 1438, so older material gives the third answer.

### Question 8 [standardese] ([basic.fundamental], [basic.compound], [expr.sizeof])

Which of these does the C++23 standard guarantee on every conforming implementation?

A. `sizeof(int*) == sizeof(char*)`
B. `sizeof(void (*)()) == sizeof(void*)`
C. `sizeof(int&) == sizeof(int*)`
D. `sizeof(std::nullptr_t) == sizeof(void*)`

**Answer (D):** `sizeof(std::nullptr_t) == sizeof(void*)`

**Why:** [basic.fundamental] states that `sizeof(std::nullptr_t)` equals `sizeof(void*)`. Only `char*` and `void*` are guaranteed to share a representation, so `int*` may differ on word-addressed machines. Function pointers can be larger than object pointers, and converting between them is only conditionally-supported. `sizeof` applied to a reference type yields the size of the referenced type, so `sizeof(int&)` is `sizeof(int)`.

---

# Track: Concurrency

Cooperative cancellation with jthread, synchronization primitives and C++20 coroutines.

# Threads, jthread, cooperative stop, and locks

> Why raw std::thread terminates on destruction, how std::jthread and stop_token provide cooperative cancellation, and how RAII locks, condition variables, latches, barriers, and semaphores coordinate concurrent execution.

- **Source:** C++ Atlas (https://cppatlas.com/topics/threads-jthread-and-locks)
- **Track:** Concurrency
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [thread.thread.class] (https://eel.is/c++draft/thread.thread.class), [thread.jthread.class] (https://eel.is/c++draft/thread.jthread.class), [thread.stoptoken] (https://eel.is/c++draft/thread.stoptoken), [thread.mutex.requirements] (https://eel.is/c++draft/thread.mutex.requirements), [thread.lock] (https://eel.is/c++draft/thread.lock), [thread.condition] (https://eel.is/c++draft/thread.condition), [thread.latch] (https://eel.is/c++draft/thread.latch), [thread.barrier] (https://eel.is/c++draft/thread.barrier), [thread.sema] (https://eel.is/c++draft/thread.sema), [thread.once.callonce] (https://eel.is/c++draft/thread.once.callonce)
- **cppreference links:** [std::thread](https://en.cppreference.com/w/cpp/thread/thread), [std::jthread](https://en.cppreference.com/w/cpp/thread/jthread), [std::stop_token](https://en.cppreference.com/w/cpp/thread/stop_token), [std::stop_source](https://en.cppreference.com/w/cpp/thread/stop_source), [std::scoped_lock](https://en.cppreference.com/w/cpp/thread/scoped_lock), [std::unique_lock](https://en.cppreference.com/w/cpp/thread/unique_lock), [std::shared_mutex](https://en.cppreference.com/w/cpp/thread/shared_mutex), [std::condition_variable_any](https://en.cppreference.com/w/cpp/thread/condition_variable_any), [std::latch](https://en.cppreference.com/w/cpp/thread/latch), [std::barrier](https://en.cppreference.com/w/cpp/thread/barrier), [std::counting_semaphore](https://en.cppreference.com/w/cpp/thread/counting_semaphore)
- **Prerequisites:** raii-and-resource-management, atomics-and-memory-ordering

Managing concurrency manually with raw OS threads breaks exception safety as soon as an early return or thrown exception leaves scope before `join()`. Modern C++ concurrency ties thread lifetime to RAII via `std::jthread`, pairs teardown with cooperative cancellation via `std::stop_token`, and layers deadlock-free lock wrappers and C++20 coordination primitives on top.

## The std::thread destructor trap and std::jthread

When a `std::thread` object is destroyed while still `joinable()`—meaning neither `join()` nor `detach()` was called—its destructor immediately invokes `std::terminate()`. The committee deliberately rejected implicit `detach()` (which leaves background workers reading destroyed stack locals) and implicit `join()` (which deadlocks if the worker waits on a condition the unwinding scope never fulfills). Even a simple helper function that creates a `std::thread`, throws an exception, and forgets a RAII wrapper aborts the process.

C++20 introduced `std::jthread` ("joining thread") to fix both lifetime and shutdown signaling. First, `~jthread()` automatically requests cancellation and joins the thread if `joinable()` is true. Second, `std::jthread` owns an internal `std::stop_source`. If your thread entry function takes `std::stop_token` as its first parameter, `std::jthread` automatically passes `get_stop_token()` without forcing you to allocate or wire a flag by hand.

> **Pitfall.** Always declare `std::jthread` as the **last** data member of any class holding mutexes, condition variables, or shared buffers used by that worker. Because class members are destroyed in reverse declaration order, placing `jthread` last guarantees `request_stop()` and `join()` complete *before* the mutex or queue is destroyed.

```cpp
#include <condition_variable>
#include <mutex>
#include <stop_token>
#include <thread>

class Worker {
    std::mutex mtx_;
    std::condition_variable_any cv_;
    bool ready_ = false;
    std::jthread thread_; // Declared LAST: stops and joins before mtx_/cv_ die

public:
    Worker()
        : thread_([this](std::stop_token st) {
              std::unique_lock lk(mtx_);
              if (!cv_.wait(lk, st, [this] { return ready_; })) {
                  return; // Stop requested while waiting
              }
          }) {}

    void signal_ready() {
        {
            std::scoped_lock lk(mtx_);
            ready_ = true;
        }
        cv_.notify_one();
    }
};
```

## Cooperative cancellation with stop_token

`std::stop_source`, `std::stop_token`, and `std::stop_callback` share a reference-counted atomic stop state. Calling `request_stop()` on the `stop_source` transitions the state once (atomically returning `true` only to the first caller) and wakes all observers holding matching `stop_token` copies. Unlike POSIX `pthread_cancel`, cancellation never injects asynchronous exceptions at arbitrary instructions; workers inspect `st.stop_requested()` at clean invariant boundaries and unwind destructors normally.

For blocking operations that cannot poll a boolean—such as waiting on a socket descriptor or an external C event loop—attach a `std::stop_callback`: its constructor registers a handler that executes when `request_stop()` fires. Crucially, if `stop_requested()` is **already** true when the `stop_callback` object is constructed, the callback runs synchronously inside the `stop_callback` constructor on the registering thread, guaranteeing zero missed cancellations.

> **Mental model.** A `stop_token` acts as a thread-safe, one-way cancellation channel with reactive callbacks—the caller requests shutdown, and the worker decides the safe point to unwind.

## Mutexes and RAII lock wrappers

Raw `mtx.lock()` and `mtx.unlock()` calls leak locked mutexes across early returns and exceptions. The standard library provides four RAII lock wrappers tailored to distinct locking patterns:

- **`std::lock_guard<M>`** acquires a single mutex on construction and releases it on destruction, with zero overhead and no move or manual-unlock methods.
- **`std::scoped_lock<Ms...>`** (C++17) generalizes `lock_guard` to variadic mutexes (`std::scoped_lock lk(m1, m2)`), using a deadlock-avoidance algorithm (`std::lock`) when given multiple locks while matching `lock_guard`'s zero overhead for a single mutex.
- **`std::unique_lock<M>`** supports deferred locking (`std::defer_lock`), timed or try locking (`std::try_to_lock`), adopting already-locked mutexes (`std::adopt_lock`), move transfer, manual `.unlock()`, and waiting on a `std::condition_variable`.
- **`std::shared_lock<SM>`** acquires shared reader access on `std::shared_mutex` or `std::shared_timed_mutex`, allowing concurrent readers while blocking exclusive `unique_lock` writers.

> **Pitfall.** Writing `std::scoped_lock(m1, m2);` or `std::unique_lock<std::mutex>(m);` without a variable name constructs an anonymous temporary that acquires the lock and immediately unlocks it at the semicolon, leaving the critical section unprotected.

| Lock Wrapper | Mutex Count | Movable & Deferrable | Manual Unlock | Primary Use Case |
| --- | --- | --- | --- | --- |
| `std::lock_guard` | Exactly 1 | No | No | Simple C++11 single-mutex critical section |
| `std::scoped_lock` | 0, 1, or many | No | No | Default single or deadlock-safe multi-mutex lock |
| `std::unique_lock` | 1 | Yes | Yes | Condition variables, lock transfer, early unlock |
| `std::shared_lock` | 1 shared mutex | Yes | Yes | Multiple concurrent readers with `shared_mutex` |

## Condition variables and spurious wakeups

`std::condition_variable` operates exclusively with `std::unique_lock<std::mutex>`, whereas `std::condition_variable_any` accepts any BasicLockable type (including `std::shared_lock` or custom locks) and provides stop-token-aware overloads such as `wait(lk, st, pred)`.

Calling bare `cv.wait(lk)` without a predicate invites two classic bugs: **lost wakeups** (the producer called `notify_one()` before the consumer reached `wait`, leaving the consumer sleeping forever) and **spurious wakeups** (operating-system futexes and scheduler signals may unblock a waiting thread even when no thread notified). Always pass a boolean predicate—`cv.wait(lk, [&] { return !queue.empty(); })`—which checks state under the lock in a loop before and after sleeping. When notifying, unlock the mutex before calling `notify_one()` or `notify_all()` whenever the condition variable itself remains alive, preventing the woken thread from immediately blocking on the still-held mutex.

> **Standardese.** Under `[thread.condition.condvar]`, `condition_variable::wait` may return spuriously without any notification; the predicate overload guarantees returning only when `bool(pred())` evaluates to `true` with `lock` reacquired (or, for `condition_variable_any::wait(lock, st, pred)`, when `st.stop_requested()` becomes `true`).

## Latches, barriers, semaphores, and call_once

C++20 added three lightweight coordination types alongside `std::call_once`:

- **`std::latch`** is a single-use downward counter (`count_down`, `wait`, `arrive_and_wait`). Any thread may call `count_down` multiple times, and waiting threads unblock once the counter reaches zero.
- **`std::barrier<CompletionFunction>`** coordinates reusable multi-phase work. When the phase arrival count reaches zero, the last arriving thread runs the completion step once before unblocking all participants and resetting the next phase (`arrive_and_wait`, `arrive_and_drop`). Under `[thread.barrier]`, `std::is_nothrow_invocable_v<CompletionFunction&>` is mandated (`noexcept`).
- **`std::counting_semaphore<LeastMaxValue>`** and **`std::binary_semaphore`** track available permits (`acquire`, `release`, `try_acquire`). Unlike `std::mutex`, semaphores impose **no thread ownership**: Thread A can `release()` a permit that Thread B later `acquire()`s, whereas unlocking a `std::mutex` from a thread that did not lock it is undefined behavior.
- **`std::once_flag` and `std::call_once`** guarantee exactly-once initialization per flag object across threads. Under `[thread.once.callonce]`, if an active invocation exits by throwing an exception, it counts as exceptional rather than returning, and another waiting invocation gets to retry.

```cpp
#include <barrier>
#include <latch>
#include <mutex>
#include <semaphore>
#include <shared_mutex>

void coordination_demo() {
    std::mutex a, b;
    {
        std::scoped_lock both(a, b); // Deadlock-free acquisition of two mutexes
    }

    std::shared_mutex rw;
    { std::shared_lock reader(rw); } // Concurrent reader access
    { std::unique_lock writer(rw); } // Exclusive writer access

    std::latch ready(1);
    ready.count_down();
    ready.wait();

    auto step_done = []() noexcept { /* runs once per phase */ };
    std::barrier phase(1, step_done);
    phase.arrive_and_wait();

    std::binary_semaphore signal{0};
    signal.release(); // Thread-agnostic signal: another thread may acquire()
    signal.acquire();
}
```

## What to remember

- Prefer `std::jthread` over `std::thread` so destructors request cancellation and join cleanly; declare `std::jthread` **last** among class members it touches.
- Pair `std::stop_token` with `std::condition_variable_any` or `std::stop_callback` for race-free cooperative shutdown without polling delays.
- Default to `std::scoped_lock` for simple or multi-mutex locking, reserve `std::unique_lock` for condition variables or deferred/manual unlocking, and always name your lock variable.
- Never call `condition_variable::wait(lk)` without a predicate; spurious and missed wakeups require checking shared state in a loop under the lock.
- Use `std::latch` for one-shot countdowns, `std::barrier` (with a `noexcept` completion callable) for phased work, and `std::binary_semaphore` instead of `std::mutex` when signaling across different threads.

## Concept Map Outline

- **Threads, jthread & locks:** RAII thread lifetimes, cooperative stop tokens, and structured synchronization prevent leaks and races.
  - **Thread ownership (thread vs jthread):** Raw std::thread aborts if unjoined; std::jthread stops and joins automatically.
    - **~thread() calls std::terminate():** Destroying a joinable std::thread aborts rather than silently detaching or deadlocking.
    - **~jthread() stops then joins:** Requests stop on its internal stop_source and joins before leaving scope.
    - **Declare jthread member last:** Reverse member destruction joins the worker before mutexes or state are destroyed.
  - **Cooperative cancellation:** stop_source and stop_token coordinate clean shutdown without async kills.
    - **stop_source & stop_token:** Reference-counted atomic stop state injected automatically into jthread callables.
    - **Synchronous stop_callback:** Runs immediately in its constructor if stop was already requested, preventing missed signals.
    - **condition_variable_any stop wait:** wait(lk, st, pred) registers a stop_callback internally to wake sleeping waiters.
  - **Mutexes & RAII locks:** Scope-bound lock wrappers match single, multi-mutex, and reader-writer patterns.
    - **scoped_lock avoids deadlocks:** Locks multiple mutexes via std::lock without ordering deadlocks.
    - **unique_lock for deferral & CVs:** Movable wrapper supporting defer_lock, early unlock(), and condition variables.
    - **shared_mutex & shared_lock:** Allows concurrent readers under shared_lock and exclusive writers under unique_lock.
    - **Unnamed lock temporary trap:** Omitting a variable name unlocks immediately at the semicolon before the guarded block.
  - **Condition variables:** Predicate waits guard against spurious wakeups and lost notifications.
    - **Always pass a predicate:** cv.wait(lk, pred) loops under the lock so spurious wakeups cannot break invariants.
    - **Unlock before notify:** Releasing the mutex prior to notify prevents woken threads from immediately stalling.
  - **C++20 coordination & call_once:** Latches, barriers, semaphores, and once_flag cover phased and cross-thread signaling.
    - **Single-use std::latch:** Downward counter where threads wait until arrivals reduce the count to zero.
    - **Reusable noexcept std::barrier:** Phased rendezvous mandating a nothrow-invocable completion callable.
    - **Unowned counting_semaphore:** Permits one thread to release() a token acquired by another thread.
    - **Exception-retrying call_once:** If the first callable throws, another waiting thread retries initialization.

## Standardese Quiz Questions

### Question 1 [warmup] ([thread.thread.destr], [thread.jthread.cons])

If do_work() throws an exception after t is launched below, what happens when stack unwinding destroys t?

```cpp
void run() {
    std::thread t([] { /* work */ });
    do_work(); // throws std::runtime_error
    t.join();
}
```

A. ~std::thread() automatically calls t.join() before propagating the exception
B. ~std::thread() automatically detaches t so it runs in the background
C. ~std::thread() calls std::terminate() because t.joinable() is still true
D. Compilation fails because std::thread requires a try/catch block

**Answer (C):** ~std::thread() calls std::terminate() because t.joinable() is still true

**Why:** Because t was neither joined nor detached before unwinding reached ~std::thread(), t.joinable() remains true. Under [thread.thread.destr], destroying a joinable std::thread immediately calls std::terminate(), unlike C++20 std::jthread, which requests stop and joins automatically.

### Question 2 [warmup] ([thread.lock.scoped])

What bug exists in the transfer function below?

```cpp
void transfer(std::mutex& m1, std::mutex& m2) {
    std::scoped_lock(m1, m2);
    // critical section modifying shared state
}
```

A. std::scoped_lock(m1, m2); creates an unnamed temporary that locks and immediately unlocks at the semicolon, leaving the critical section unprotected
B. std::scoped_lock deadlocks when passed two mutexes
C. std::scoped_lock only accepts one mutex in C++23
D. The function leaks both mutexes when returning

**Answer (A):** std::scoped_lock(m1, m2); creates an unnamed temporary that locks and immediately unlocks at the semicolon, leaving the critical section unprotected

**Why:** Because no variable name is given, std::scoped_lock(m1, m2); constructs a temporary object whose lifetime ends at the semicolon, unlocking m1 and m2 right before the critical section executes. Writing std::scoped_lock lk(m1, m2); binds a named guard to the scope.

### Question 3 [tricky] ([class.dtor], [thread.jthread.destr])

Look closely at the member declaration order inside Pipeline. Why is ~Pipeline() unsafe when Pipeline goes out of scope?

```cpp
class Pipeline {
    std::jthread worker_;
    std::mutex mtx_;
    bool active_ = true;
public:
    Pipeline() : worker_([this](std::stop_token st) {
        while (!st.stop_requested()) {
            std::scoped_lock lk(mtx_);
            if (!active_) break;
        }
    }) {}
};
```

A. std::jthread cannot capture this in its constructor lambda
B. std::scoped_lock cannot be constructed inside a while loop
C. ~jthread() does not call request_stop() unless stop_source is passed manually
D. Members are destroyed in reverse declaration order, so mtx_ is destroyed BEFORE ~jthread() requests stop and joins worker_

**Answer (D):** Members are destroyed in reverse declaration order, so mtx_ is destroyed BEFORE ~jthread() requests stop and joins worker_

**Why:** Class data members are always destroyed in reverse order of declaration ([class.dtor]). Because worker_ is declared first, mtx_ and active_ are destroyed first while worker_ is still running its loop—invoking undefined behavior. Declaring std::jthread worker_; last guarantees it stops and joins before mtx_ and active_ die.

### Question 4 [tricky] ([thread.mutex.requirements.mutex], [thread.sema.cnt])

Thread A needs to signal Thread B that a buffer is ready, so Thread B can proceed and unblock. Which synchronization primitive is legal when Thread A unlocks/signals and Thread B acquires?

A. Locking a std::mutex on Thread B and calling m.unlock() from Thread A
B. Calling sem.release() on Thread A and sem.acquire() on Thread B with std::binary_semaphore sem{0}
C. Destroying a std::lock_guard created on Thread A from Thread B
D. Using std::shared_lock on Thread A and unlocking it from Thread B

**Answer (B):** Calling sem.release() on Thread A and sem.acquire() on Thread B with std::binary_semaphore sem{0}

**Why:** std::mutex has strict thread ownership: unlocking a mutex from a thread that does not own the lock is undefined behavior ([thread.mutex.requirements.mutex]). By contrast, std::counting_semaphore and std::binary_semaphore have no thread ownership—any thread may call release() while another calls acquire().

### Question 5 [standardese] ([thread.condition.condvarany])

Why does std::condition_variable_any::wait(lk, st, pred) still check pred() inside a loop, even with a std::stop_token?

A. Only std::condition_variable suffers from spurious wakeups; condition_variable_any never wakes spuriously
B. A stop_token disables mutex locking inside condition_variable_any
C. Condition variable waits may experience spurious wakeups ([thread.condition.condvarany]), so the overload loops until either pred() returns true or st.stop_requested() becomes true
D. wait(lk, st, pred) throws std::system_error when st.stop_requested() is true

**Answer (C):** Condition variable waits may experience spurious wakeups ([thread.condition.condvarany]), so the overload loops until either pred() returns true or st.stop_requested() becomes true

**Why:** Under [thread.condition.condvarany], wait(lock, stoken, pred) repeatedly waits while !stoken.stop_requested() and !pred(), returning pred() once either the predicate holds or stop was requested. This handles both spurious wakeups and stop requests delivered before or during the wait.

### Question 6 [standardese] ([thread.barrier], [thread.once.callonce])

Which statement accurately captures the C++ standard rules for std::barrier's CompletionFunction and std::call_once's callable if exceptions occur?

A. std::barrier catches and ignores exceptions thrown by CompletionFunction, while std::call_once marks the once_flag permanently failed on exception
B. Both std::barrier and std::call_once call std::terminate() if their callables throw
C. Neither std::barrier nor std::call_once constrains exceptions on its callable
D. std::barrier mandates std::is_nothrow_invocable_v<CompletionFunction&> (noexcept), whereas an exception from std::call_once leaves the once_flag uncompleted so another thread retries

**Answer (D):** std::barrier mandates std::is_nothrow_invocable_v<CompletionFunction&> (noexcept), whereas an exception from std::call_once leaves the once_flag uncompleted so another thread retries

**Why:** Under [thread.barrier], std::barrier<CompletionFunction> requires is_nothrow_invocable_v<CompletionFunction&> to be true (a non-noexcept completion callable is ill-formed). Under [thread.once.callonce], an invocation of std::call_once that exits via an exception is classified as an exceptional execution rather than returning, allowing a subsequent waiting invocation to try again.

# Threads and jthread

> A std::thread is an owning handle that you must join or detach before it dies, and it copies its arguments before the new thread starts. C++20's std::jthread joins for you and adds cooperative cancellation through stop tokens.

- **Source:** C++ Atlas (https://cppatlas.com/topics/threads-and-jthread)
- **Track:** Concurrency
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [thread.thread.class] (https://eel.is/c++draft/thread.thread.class), [thread.thread.constr] (https://eel.is/c++draft/thread.thread.constr), [thread.thread.destr] (https://eel.is/c++draft/thread.thread.destr), [thread.thread.member] (https://eel.is/c++draft/thread.thread.member), [thread.thread.static] (https://eel.is/c++draft/thread.thread.static), [thread.thread.id] (https://eel.is/c++draft/thread.thread.id), [thread.jthread.class] (https://eel.is/c++draft/thread.jthread.class), [thread.stoptoken] (https://eel.is/c++draft/thread.stoptoken), [stopcallback] (https://eel.is/c++draft/stopcallback), [basic.stc.thread] (https://eel.is/c++draft/basic.stc.thread), [basic.start.term] (https://eel.is/c++draft/basic.start.term)
- **cppreference links:** [std::thread](https://en.cppreference.com/w/cpp/thread/thread), [std::thread::~thread](https://en.cppreference.com/w/cpp/thread/thread/~thread), [std::jthread](https://en.cppreference.com/w/cpp/thread/jthread), [std::stop_token](https://en.cppreference.com/w/cpp/thread/stop_token), [std::stop_callback](https://en.cppreference.com/w/cpp/thread/stop_callback), [std::thread::hardware_concurrency](https://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency), [std::ref, std::cref](https://en.cppreference.com/w/cpp/utility/functional/ref), [Storage class specifiers (thread_local)](https://en.cppreference.com/w/cpp/language/storage_duration)
- **Prerequisites:** atomics-and-memory-ordering, raii-and-resource-management, lambdas

## The one idea

A `std::thread` object is not the thread. It is a handle that may own one thread of execution, much as a `unique_ptr` may own one heap object. The handle is movable and not copyable, and while it owns a thread it is called *joinable*. Every joinable handle must give up ownership before it is destroyed, either by `join()`, which waits for the thread to finish, or by `detach()`, which lets it run on unowned. If you forget, the destructor does not guess which one you meant. It calls `std::terminate`.

C++20's `std::jthread` is the same handle with a different policy: its destructor asks the thread to stop and then joins it. That one change makes threads behave like any other RAII resource, and the stop request turns into a small, cooperative cancellation framework.

> **Mental model.** A thread handle is a debt. Constructing a joinable `std::thread` creates the debt, and only `join` or `detach` pays it. `std::jthread` pays it automatically, by asking politely and then waiting.

The rules about data races, happens-before and atomics are covered in atomics-and-memory-ordering. This page is about the thread objects themselves, and the two synchronization edges they create: the end of the constructor synchronizes with the start of the new thread's function, and the completion of the thread synchronizes with the return from `join()`.

## Constructing a thread: what gets copied, and where

The constructor takes a callable and arguments, and the new thread invokes the callable on them. The important detail is that every argument is first decay-copied *in the constructing thread*, and those copies are then passed to the function as rvalues in the new thread. Since C++23 the standard spells this as `invoke(auto(std::forward<F>(f)), auto(std::forward<Args>(args))...)` with the `auto` values materialized in the calling thread.

Three consequences follow. A function taking `int&` cannot be started with a plain `int` argument, because an rvalue copy cannot bind to a non-const lvalue reference. A function taking `const int&` compiles but receives a reference to the private copy, not to your variable. And if you really want to share the variable, you wrap it in `std::ref`, which produces a `reference_wrapper` that is copied cheaply and converts to `int&` at the call.

```cpp
#include <functional>
#include <thread>

void inc(int& n) { ++n; }

int main() {
  int x = 0;
  // std::thread bad(inc, x);       // ill-formed: the copy of x is an rvalue
  std::thread t(inc, std::ref(x));  // OK: inc sees x itself
  t.join();                         // join makes the write visible: x == 1
}
```

Exceptions thrown while copying the arguments surface in the constructing thread, which is the only place they could be handled. If the system cannot create a thread at all, the constructor throws `std::system_error` with `resource_unavailable_try_again`. Member functions work as usual through `std::invoke`, so `std::thread t(&Worker::run, &w, 5);` calls `w.run(5)`.

> **Pitfall.** Decay-copying happens to the argument as written, not to the parameter type. Passing a `char` array to a function taking `const std::string&` copies a `char*`, and the `std::string` is only built when the new thread calls the function. If the array was a local in a function that has already returned, the new thread reads a dead buffer. Convert explicitly, as `std::string(buf)`, so that the string is what gets copied.

## Joinable means you owe a join

A thread handle is joinable from successful construction until it is joined, detached, or moved from. A default-constructed handle is not joinable. Destroying a joinable `std::thread`, or move-assigning a new thread into one, calls `std::terminate`.

```cpp
#include <thread>

int main() {
  std::thread a([] {});
  std::thread b([] {});
  // a = std::move(b);   // would call std::terminate: a is still joinable
  a.join();
  a = std::move(b);      // fine: a is empty now, and takes over b's thread
  a.join();
}
```

The termination rule was a deliberate choice. Joining implicitly could deadlock an unwinding stack waiting on a thread that is waiting on the unwinding code; detaching implicitly could leave a thread running against destroyed locals. Neither is safe to do silently, so the standard refuses both.

> **Standardese.** [thread.thread.destr] says that if the handle is joinable when it is destroyed, `std::terminate` is called; otherwise the destructor has no effects. [thread.thread.member] adds that `join()` throws `std::system_error` with `resource_deadlock_would_occur` if a thread tries to join itself, and with `invalid_argument` if the handle is not joinable.

## Exceptions do not cross the thread boundary

An exception thrown by the thread's function cannot propagate into the thread that created it, because that thread is off doing something else. If the function exits with an uncaught exception, `std::terminate` is called, and no `try` block around the thread's constructor or `join()` can intercept it. To report failure to another thread, catch inside the thread function and hand over a `std::exception_ptr`, or use a `std::promise` or `std::packaged_task`, which carry exceptions to a future. The topic futures-promises-and-async covers that machinery.

```cpp
#include <exception>
#include <stdexcept>
#include <thread>

int main() {
  std::exception_ptr error;
  std::thread t([&] {
    try { throw std::runtime_error("boom"); }
    catch (...) { error = std::current_exception(); }  // capture, do not escape
  });
  t.join();                       // join orders the write to error before this
  if (error) { /* std::rethrow_exception(error) here, in the joining thread */ }
}
```

## std::jthread and cooperative cancellation

`std::jthread`, added in C++20, owns a `std::stop_source`. Its destructor calls `request_stop()` and then `join()` if the handle is joinable, and so does its move assignment before taking over the new thread. If the callable accepts a `std::stop_token` as its first parameter, the constructor passes the token from its stop source automatically; otherwise it calls the callable exactly as `std::thread` would.

```cpp
#include <chrono>
#include <stop_token>
#include <thread>

int main() {
  std::jthread worker([](std::stop_token st) {
    while (!st.stop_requested()) {
      std::this_thread::sleep_for(std::chrono::milliseconds(1));  // a unit of work
    }
  });
}   // ~jthread: request_stop(), then join(); main returns normally
```

Cancellation is cooperative. Nothing interrupts the thread; it must poll `stop_requested()`, or block in something that understands stop tokens, such as `std::condition_variable_any`'s waits, which condition-variables-and-waiting covers. The three types divide the work. A `std::stop_source` makes requests, a `std::stop_token` observes one shared stop state, and a `std::stop_callback` registers a function to run when stop is requested. `request_stop()` returns `true` only for the call that actually makes the request, and `stop_possible()` on a token is `false` when it has no stop state or when no source remains that could still request a stop.

A `std::stop_callback` runs its function synchronously in the thread that makes the successful `request_stop()` call. If stop has already been requested when the callback is constructed, the function runs immediately, in the constructing thread, before the constructor returns. The callback's destructor deregisters it, and if the callback is running on another thread at that moment, the destructor waits for it to finish. A callback that exits by an exception calls `std::terminate`.

```cpp
#include <cstdio>
#include <stop_token>

int main() {
  std::stop_source src;
  bool first = src.request_stop();   // true: this call made the request
  bool again = src.request_stop();   // false: stop was already requested
  std::stop_callback cb(src.get_token(), [] { std::puts("callback"); });
  // "callback" was printed by the constructor, in this thread
  std::printf("%d %d\n", first, again);   // 1 0
}
```

Callbacks are how you wire a stop request into code that blocks elsewhere, for instance by closing a socket or notifying a condition variable when stop is requested.

## Detaching, thread ids and hardware_concurrency

`detach()` gives up ownership and lets the thread run to completion on its own. It is rarely what you want. A detached thread cannot be joined, so nothing tells you when it has finished with the objects it references, and lambdas that capture locals by reference become dangling as soon as the enclosing function returns. Shutdown is worse: when `main` returns, static objects are destroyed while detached threads may still be running. [basic.start.term] makes any use of the standard library that does not happen before that destruction undefined behavior, so a detached thread that is still writing to `std::cout` during shutdown is undefined behavior. If you must detach, signal completion with `std::notify_all_at_thread_exit` or a promise's `set_value_at_thread_exit`, which fire after the thread's `thread_local` objects are destroyed.

Each thread has a `std::thread::id`, available from `get_id()` on the handle or `std::this_thread::get_id()` inside the thread. A non-joinable handle reports a default-constructed id, which represents no thread. Ids are totally ordered, hashable, and printable, but the id of a finished thread may be reused for a new one.

`std::thread::hardware_concurrency()` returns the number of hardware thread contexts as a hint, and returns 0 when the value is not computable or not well defined. Code that sizes a thread pool from it should clamp the result to at least 1.

## thread_local objects and thread exit

A variable declared `thread_local` has thread storage duration: each thread gets its own instance, created for that thread and destroyed when the thread ends. A block-scope `thread_local` is initialized the first time each thread passes through its declaration. For a namespace-scope `thread_local` with dynamic initialization, it is implementation-defined whether initialization happens at thread start or is deferred until the first use in that thread.

Constructed `thread_local` objects are destroyed, in reverse order of construction, as part of the thread returning from its initial function or calling `std::exit`. That destruction is part of the thread's completion, so it happens before `join()` returns. In the main thread, all `thread_local` destructors finish before any static object is destroyed. A thread that ends through `std::terminate` or `std::quick_exit` does not run them.

```cpp
#include <cstdio>
#include <thread>

struct Noisy { ~Noisy() { std::puts("dtor"); } };

int main() {
  std::thread t([] {
    thread_local Noisy n;   // one per thread, constructed on first pass here
    std::puts("body");
  });
  t.join();                 // "body", then "dtor", both before join returns
  std::puts("joined");
}
```

> **Pitfall.** A `thread_local` destructor that touches another `thread_local`, or a static, can run after that object is gone. Treat thread exit like program exit: destruction order is reverse construction order within the thread, and anything outside that order is your problem.

## What to remember

- Destroying or move-assigning over a joinable `std::thread` calls `std::terminate`. Join or detach every thread.
- Arguments are decay-copied in the constructing thread and passed as rvalues. Use `std::ref` to share, and convert pointers to owning types before the copy.
- An exception escaping a thread function calls `std::terminate`. Carry errors across with `exception_ptr`, promises or `packaged_task`.
- Thread construction synchronizes with the start of the thread, and thread completion synchronizes with the return of `join()`.
- `std::jthread` (C++20) requests stop and joins in its destructor and passes a `stop_token` if the callable takes one.
- Cancellation is cooperative. `request_stop()` returns true once, and a `stop_callback` runs in the requesting thread, or immediately if stop was already requested.
- Detached threads cannot be waited for; using the standard library after static destruction begins is undefined behavior.
- `hardware_concurrency()` may return 0. Thread ids of finished threads may be reused.
- `thread_local` objects are destroyed at thread exit, before `join()` returns, and before statics in the main thread.

## Concept Map Outline

- **Threads and jthread:** A thread handle owns at most one thread and must join or detach it; jthread stops and joins for you.
  - **Construction:** The callable and arguments are decay-copied in the calling thread, then invoked as rvalues.
    - **int& parameters:** A plain argument cannot bind to int&; the call is ill-formed without std::ref.
    - **std::ref:** Passes a reference_wrapper, so the thread sees the original object; it must outlive the use.
    - **Deferred conversion:** A char array is copied as char*; the std::string parameter is built later, in the new thread.
    - **Start synchronizes:** The end of the constructor synchronizes with the start of the thread's function.
  - **Joinable lifecycle:** Joinable from construction until join, detach or move; default-constructed handles are not.
    - **Destructor terminates:** Destroying or move-assigning over a joinable std::thread calls std::terminate.
    - **join:** Thread completion synchronizes with join's return; self-join throws resource_deadlock_would_occur.
    - **detach:** Nothing can wait for it later; using the library after static destruction starts is undefined.
  - **Exceptions:** Exceptions never cross from one thread to another.
    - **Escape terminates:** An exception leaving the thread function calls std::terminate; try around join cannot catch it.
    - **Carry it across:** Catch inside, store a std::exception_ptr, or use a promise or packaged_task.
  - **std::jthread (C++20):** Owns a stop_source; the destructor calls request_stop() and then join().
    - **Token injection:** If the callable takes a stop_token first, jthread passes its own token automatically.
    - **Cooperative:** Nothing interrupts the thread; it must poll stop_requested or block in a stop-aware wait.
    - **request_stop:** Returns true only for the call that actually makes the request.
    - **stop_callback:** Runs in the requesting thread, or at once in its constructor if stop was already requested.
    - **stop_possible:** False with no stop state, or when no stop_source remains that could still request.
  - **Identity and hints:** Ids name threads; hardware_concurrency is only advice.
    - **thread::id:** Default id means no thread; ids are ordered and hashable, and may be reused after a thread ends.
    - **hardware_concurrency:** Number of hardware thread contexts as a hint; may return 0.
  - **thread_local:** Each thread has its own instance, destroyed when that thread exits.
    - **Initialization:** Block scope: first pass in each thread. Namespace scope: may be deferred until first use.
    - **Destruction:** Reverse construction order at thread exit, completed before join returns.
    - **Main thread:** Main's thread_local objects are destroyed before any static-storage object.

## Standardese Quiz Questions

### Question 1 [warmup] ([thread.thread.destr])

What happens when this program reaches the end of `main`?

```cpp
#include <cstdio>
#include <thread>

int main() {
  std::thread t([] {});
  std::puts("leaving main");
}
```

A. The destructor of `t` joins the thread, and the program exits normally
B. The destructor of `t` detaches the thread, and the program exits normally
C. Undefined behavior
D. `std::terminate` is called

**Answer (D):** `std::terminate` is called

**Why:** `t` is still joinable when it is destroyed, because nobody called `join()` or `detach()`. [thread.thread.destr] specifies that destroying a joinable `std::thread` calls `std::terminate`, so this is well-defined termination rather than undefined behavior. Implicit joining is what `std::jthread` does; `std::thread` deliberately refuses to pick either policy for you.

### Question 2 [warmup] ([thread.thread.constr], [refwrap])

Is this program well-formed?

```cpp
#include <thread>

void inc(int& n) { ++n; }

int main() {
  int x = 0;
  std::thread t(inc, x);
  t.join();
}
```

A. Well-formed, and `x` is 1 after the join
B. Well-formed, but `inc` increments a copy, so `x` stays 0
C. Ill-formed: the decay-copied argument is an rvalue and cannot bind to `int&`
D. Undefined behavior: data race on `x`

**Answer (C):** Ill-formed: the decay-copied argument is an rvalue and cannot bind to `int&`

**Why:** The thread constructor decay-copies each argument in the calling thread and passes the copies to the function as rvalues. An rvalue `int` cannot bind to `int&`, so the constructor's requirement that the call be invocable fails and the program does not compile. The second option describes what happens for a `const int&` parameter. Passing `std::ref(x)` makes it compile and increment `x` itself.

### Question 3 [warmup] ([thread.jthread.class], [thread.stoptoken])

In C++20, what does this program do?

```cpp
#include <cstdio>
#include <stop_token>
#include <thread>

int main() {
  std::jthread t([](std::stop_token st) {
    while (!st.stop_requested()) {}
    std::puts("stopped");
  });
  std::puts("main done");
}
```

A. Prints `main done`, then `stopped`, and exits normally
B. Calls `std::terminate`, because `t` is joinable when destroyed
C. Hangs forever, because nothing calls `request_stop`
D. Prints `main done` and exits; the loop is killed with the process

**Answer (A):** Prints `main done`, then `stopped`, and exits normally

**Why:** `std::jthread` passes its own stop token to a callable whose first parameter is a `std::stop_token`. Its destructor calls `request_stop()` and then `join()`, so the loop sees the request, prints `stopped`, and the join returns. Termination on a joinable destructor is the `std::thread` rule, which `jthread` replaces, and the hang would only happen if the destructor joined without requesting stop.

### Question 4 [tricky] ([thread.thread.constr], [basic.life])

Which statement about `start` is correct?

```cpp
#include <string>
#include <thread>

void show(const std::string& s);

void start() {
  char buf[32] = "hello";
  std::thread t(show, buf);
  t.detach();
}
```

A. It is safe: the `std::string` is built from `buf` before the constructor returns
B. It is ill-formed: a `char` array cannot be passed to a `const std::string&` parameter
C. It is safe because `detach` waits until the arguments have been consumed
D. The new thread may build the string from a dangling `char*` after `start` returns, which is undefined behavior

**Answer (D):** The new thread may build the string from a dangling `char*` after `start` returns, which is undefined behavior

**Why:** Decay-copying applies to the argument as written, so the thread stores a copy of the `char*` that `buf` decays to. The conversion to `std::string` happens when the new thread calls `show`, which may be after `start` has returned and `buf` is gone. Converting at the call site, as `std::string(buf)`, makes the string itself the stored copy. The first option is what most people assume, but the constructor only copies; it never applies the parameter's conversion.

### Question 5 [tricky] ([thread.thread.constr], [except.terminate])

What does this program do?

```cpp
#include <cstdio>
#include <stdexcept>
#include <thread>

int main() {
  try {
    std::thread t([] { throw std::runtime_error("boom"); });
    t.join();
  } catch (...) {
    std::puts("caught");
  }
}
```

A. Prints `caught`, because `join` rethrows the thread's exception
B. Prints `caught`, because the exception unwinds into the creating thread
C. Calls `std::terminate`; `caught` is never printed
D. Undefined behavior

**Answer (C):** Calls `std::terminate`; `caught` is never printed

**Why:** [thread.thread.constr] says that if the thread's function exits with an uncaught exception, `std::terminate` is called. Exceptions do not cross thread boundaries, and `join` has no channel to carry one. Rethrowing on retrieval is what `std::future::get` does, which is the tempting confusion. To report errors, catch in the thread and pass a `std::exception_ptr` or use a promise.

### Question 6 [tricky] ([stopsource], [stopcallback])

In C++20, what does this program print?

```cpp
#include <cstdio>
#include <stop_token>

int main() {
  std::stop_source src;
  bool first = src.request_stop();
  bool second = src.request_stop();
  std::stop_callback cb(src.get_token(), [] { std::puts("callback"); });
  std::printf("%d %d\n", first, second);
}
```

A. `1 1`, and the callback never runs because it was registered too late
B. `callback` then `1 0`
C. `1 0` then `callback`, printed when `cb` is destroyed
D. `1 0`, and the callback never runs because it was registered too late

**Answer (B):** `callback` then `1 0`

**Why:** `request_stop` returns `true` only for the call that actually makes the stop request, so the second call returns `false`. A `stop_callback` constructed after stop has been requested invokes its callback immediately, in the constructing thread, before the constructor returns. That is why `callback` is printed first. A callback registered late is never lost, which rules out the first and last options.

### Question 7 [standardese] ([thread.thread.static])

What does the standard guarantee about the value of `std::thread::hardware_concurrency()`?

A. It is at least 1, since the calling thread is running on some hardware context
B. It is the maximum number of `std::thread` objects that can be joinable at once
C. It equals the number of physical cores
D. It is a hint about hardware thread contexts, and may be 0 if not computable or not well defined

**Answer (D):** It is a hint about hardware thread contexts, and may be 0 if not computable or not well defined

**Why:** [thread.thread.static] describes the value as the number of hardware thread contexts, to be regarded only as a hint, and says it returns 0 when the value is not computable or well defined. Nothing promises it is at least 1, so code that sizes a pool from it should clamp. It says nothing about how many threads may be created, and hardware thread contexts typically count simultaneous multithreading siblings, not physical cores.

### Question 8 [standardese] ([basic.start.term], [basic.stc.thread], [thread.thread.member])

What is guaranteed to be printed?

```cpp
#include <cstdio>
#include <thread>

struct Noisy {
  ~Noisy() { std::puts("dtor"); }
};

int main() {
  std::thread t([] {
    thread_local Noisy n;
    std::puts("body");
  });
  t.join();
  std::puts("joined");
}
```

A. `body`, `joined`, `dtor`: thread-local objects are destroyed at program exit
B. `body`, `dtor`, `joined`
C. `body` and `joined`, with `dtor` in an unspecified position
D. `body` and `joined` only: thread-local objects of other threads are never destroyed

**Answer (B):** `body`, `dtor`, `joined`

**Why:** Constructed objects with thread storage duration are destroyed as a result of the thread returning from its initial function, per [basic.start.term], so their destruction is part of that thread's completion. [thread.thread.member] says the thread's completion synchronizes with the successful return of `join()`. So `dtor` is printed before `join` returns, and therefore before `joined`. The first option confuses thread storage with static storage, which is destroyed at program exit.

# Mutexes and locks

> A mutex turns a region of code into a critical section and creates happens-before between whoever unlocks and whoever locks next. This page covers the mutex kinds, the RAII lock wrappers, deadlock and std::lock, the undefined behavior that is easy to write, and one-time initialization.

- **Source:** C++ Atlas (https://cppatlas.com/topics/mutexes-and-locks)
- **Track:** Concurrency
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [thread.req.lockable] (https://eel.is/c++draft/thread.req.lockable), [thread.mutex.requirements] (https://eel.is/c++draft/thread.mutex.requirements), [thread.mutex.class] (https://eel.is/c++draft/thread.mutex.class), [thread.mutex.recursive] (https://eel.is/c++draft/thread.mutex.recursive), [thread.timedmutex.requirements] (https://eel.is/c++draft/thread.timedmutex.requirements), [thread.sharedmutex.requirements] (https://eel.is/c++draft/thread.sharedmutex.requirements), [thread.lock.guard] (https://eel.is/c++draft/thread.lock.guard), [thread.lock.scoped] (https://eel.is/c++draft/thread.lock.scoped), [thread.lock.unique] (https://eel.is/c++draft/thread.lock.unique), [thread.lock.shared] (https://eel.is/c++draft/thread.lock.shared), [thread.lock.algorithm] (https://eel.is/c++draft/thread.lock.algorithm), [thread.once.callonce] (https://eel.is/c++draft/thread.once.callonce), [stmt.dcl] (https://eel.is/c++draft/stmt.dcl)
- **cppreference links:** [std::mutex](https://en.cppreference.com/w/cpp/thread/mutex), [std::shared_mutex](https://en.cppreference.com/w/cpp/thread/shared_mutex), [Named requirements: Lockable](https://en.cppreference.com/w/cpp/named_req/Lockable), [std::scoped_lock](https://en.cppreference.com/w/cpp/thread/scoped_lock), [std::unique_lock](https://en.cppreference.com/w/cpp/thread/unique_lock), [std::lock](https://en.cppreference.com/w/cpp/thread/lock), [std::call_once](https://en.cppreference.com/w/cpp/thread/call_once), [Storage class specifiers (static local variables)](https://en.cppreference.com/w/cpp/language/storage_duration)
- **Prerequisites:** threads-and-jthread, atomics-and-memory-ordering, raii-and-resource-management

## The one idea

A mutex is a token that at most one thread holds at a time. Code that runs only while holding it is a critical section, and two critical sections guarded by the same mutex never overlap. That is the half everyone knows. The other half is ordering: every `lock` and `unlock` on a given mutex falls into one total order, and each `unlock` synchronizes with the next `lock` that acquires the mutex. So whatever a thread wrote before unlocking is visible to whoever locks after it. That is why plain, non-atomic data guarded consistently by one mutex has no data race. The definitions of data race and happens-before are in atomics-and-memory-ordering.

> **Mental model.** A mutex guards an invariant, not a variable. Lock, find the invariant true, break it briefly, restore it, unlock. Every access to the data the invariant covers, reads included, must hold the same mutex.

The rest is plumbing: which kind of mutex, which RAII wrapper, how to lock several without deadlock, and the handful of mistakes the standard declares undefined.

## The mutex family and the Lockable requirements

The library describes lockable things by named requirements rather than by a base class, so your own types can take part.

| Requirement | Operations | Examples |
|---|---|---|
| *Cpp17BasicLockable* | `lock`, `unlock` | anything `lock_guard` accepts |
| *Cpp17Lockable* | adds `try_lock` | what `std::lock` and a multi-mutex `scoped_lock` need |
| *Cpp17TimedLockable* | adds `try_lock_for`, `try_lock_until` | `timed_mutex` |

The standard mutex types build on those:

- `std::mutex` is the plain exclusive mutex. Its default constructor is `constexpr`, so a namespace-scope `std::mutex` is constant-initialized and has no static initialization order problem.
- `std::recursive_mutex` lets the owning thread lock again; it must unlock as many times as it locked. The maximum depth is unspecified, and exceeding it makes `lock` throw `std::system_error` and `try_lock` return false.
- `std::timed_mutex` and `std::recursive_timed_mutex` add timed attempts.
- `std::shared_timed_mutex` (C++14) and `std::shared_mutex` (C++17) add a shared mode: many threads may hold `lock_shared` at once, but `lock` excludes everyone. There is no upgrade from shared to exclusive, and the standard does not specify whether readers or writers get priority.

None of these is copyable or movable. A mutex is an identity; its address is what threads agree on.

One detail of `try_lock` surprises people: [thread.mutex.requirements.mutex] allows it to fail even when no other thread owns the mutex. A failed `try_lock` also does not synchronize with anything. Use it to avoid blocking, never to learn what another thread is doing.

```cpp
#include <map>
#include <mutex>
#include <shared_mutex>
#include <string>

class Registry {
  mutable std::shared_mutex m_;
  std::map<std::string, int> items_;
public:
  int find(const std::string& k) const {
    std::shared_lock lock(m_);   // many readers at once
    auto it = items_.find(k);
    return it == items_.end() ? -1 : it->second;
  }
  void set(const std::string& k, int v) {
    std::unique_lock lock(m_);   // one writer, and no readers
    items_[k] = v;
  }
};
```

## Lock wrappers: lock_guard, unique_lock, scoped_lock, shared_lock

Calling `lock` and `unlock` by hand is fragile, because an exception or early return between them leaves the mutex locked. The wrappers tie ownership to scope.

- `std::lock_guard<M>` locks in its constructor and unlocks in its destructor. It is neither copyable nor movable. The `std::adopt_lock` tag makes it take over a mutex the thread already holds.
- `std::scoped_lock<Ms...>` (C++17) is the variadic successor. With one mutex it behaves like `lock_guard`; with several it locks them all through the deadlock-avoiding `std::lock` algorithm.
- `std::unique_lock<M>` is movable and may or may not own the mutex at any moment. It accepts `std::defer_lock`, `std::try_to_lock`, `std::adopt_lock` and timeouts, and offers `lock`, `unlock`, `owns_lock` and `release`, which gives up the association *without* unlocking. It is the type `std::condition_variable` requires, and it costs a flag and a branch more than `lock_guard`.
- `std::shared_lock<M>` (C++14) is the shared-mode counterpart of `unique_lock`, calling `lock_shared` and `unlock_shared`.

`unique_lock` checks its own state. Calling `unlock` when it does not own the mutex throws `std::system_error` with `operation_not_permitted`, and calling `lock` when it already owns throws with `resource_deadlock_would_occur`.

> **Pitfall.** A lock wrapper must be a named variable. `std::scoped_lock{m};` creates a temporary that locks and unlocks within that one statement. `std::unique_lock<std::mutex>(m);` is worse: the parentheses are redundant declarator parentheses, so it declares a new, default-constructed `unique_lock` named `m` that owns nothing and shadows the mutex. Both compile, and both leave the code that follows unprotected. GCC's `-Wparentheses` and Clang's `-Wvexing-parse` catch the second form.

## Deadlock and std::lock

Deadlock needs a cycle: thread 1 holds A and waits for B, while thread 2 holds B and waits for A. The classic cure is a global lock order, so a cycle cannot form. When the order is not knowable, as when transferring between two accounts chosen at run time, `std::lock(m1, m2, ...)` locks any number of *Cpp17Lockable* objects without deadlock. The standard leaves its algorithm unspecified, saying only that it uses `lock`, `try_lock` and `unlock` and avoids deadlock. Typical implementations lock one mutex, `try_lock` the rest, and on failure release everything and retry, starting with the mutex that could not be taken. If an exception escapes, every mutex it had locked is unlocked again.

```cpp
#include <mutex>

struct Account {
  std::mutex m;
  long balance = 0;
};

void transfer(Account& from, Account& to, long amount) {
  // Two threads calling transfer(a, b) and transfer(b, a) cannot deadlock.
  std::scoped_lock lock(from.m, to.m);   // uses the std::lock algorithm
  from.balance -= amount;
  to.balance += amount;
}
```

Before C++17 the same thing took two steps: `std::lock(a, b)` followed by two `lock_guard`s with `std::adopt_lock`, or two `unique_lock`s with `std::defer_lock` passed to `std::lock`. `std::try_lock(m1, m2, ...)` is the non-blocking relative: it returns -1 if it locked everything, or the zero-based index of the first argument it failed to lock, having unlocked the rest.

Note that `std::lock` only prevents deadlock among the mutexes passed to one call. A thread that already holds some other mutex can still be part of a cycle.

## Undefined behavior you can write in one line

The mutex requirements are stated as preconditions, and breaking a precondition of a standard library function is undefined behavior. Four cases account for most real bugs.

- Locking a `std::mutex`, `timed_mutex`, `shared_mutex` or `shared_timed_mutex` that the calling thread already owns. Many implementations deadlock, and a note in [thread.mutex.class] says one that detects it might report `resource_deadlock_would_occur`, but the standard promises neither.
- Calling `unlock` from a thread that does not own the mutex. A mutex is not a semaphore, and there is no handing it to another thread to release.
- Destroying a mutex while any thread owns it.
- Letting a thread end while it owns a mutex.

```cpp
#include <mutex>

std::mutex m;

void helper() { std::lock_guard lk(m); /* ... */ }

void api() {
  std::lock_guard lk(m);
  helper();   // undefined behavior: m is a std::mutex and this thread owns it
}
```

> **Standardese.** [thread.mutex.requirements.mutex] makes "the calling thread does not own the mutex" a precondition of `lock` for the non-recursive types and "the calling thread owns the mutex" a precondition of `unlock`. [thread.mutex.class] separately says that the behavior is undefined if a program destroys a mutex owned by any thread, or if a thread terminates while owning one.

`std::recursive_mutex` makes the first case legal, but it usually hides a design problem: a function that is entered with the invariant already broken. Splitting the code into a public function that locks and a private one that assumes the lock is held is almost always cleaner.

## call_once and thread-safe statics

Lazy one-time initialization has two standard forms. The first is a block-scope static. Since C++11, if several threads reach the declaration at once, one initializes the variable and the rest wait for it to finish. If the initializer throws, the variable is not initialized, and the next thread to arrive tries again. Re-entering the declaration recursively while it is being initialized is undefined behavior. In testing for this page, the GCC 16 build hung, while the Clang build with libc++ aborted with a diagnostic.

```cpp
struct Config { int verbosity = 1; };

Config& config() {
  static Config c;   // initialized exactly once, thread-safe since C++11
  return c;
}
```

The second is `std::call_once` with a `std::once_flag`, for when the state is not a single static, for example a member of an object. All calls on one flag are ordered. The call that runs the callable and returns normally is a *returning* execution, and it synchronizes with every *passive* call that finds the work already done. If the callable throws, the execution is *exceptional*: the exception propagates to that caller, the flag stays unset, and a later call runs the callable again.

```cpp
#include <mutex>
#include <vector>

class Table {
  std::once_flag built_;
  std::vector<int> data_;
public:
  const std::vector<int>& get() {
    std::call_once(built_, [this] { data_.assign(1024, 0); });
    return data_;   // every caller sees the fully built vector
  }
};
```

## Granularity, and calling code you do not control

A mutex serializes everything it covers, so hold it for the shortest stretch that keeps the invariant intact. Prepare values before locking, and do slow work such as I/O and allocation-heavy formatting after unlocking. Splitting one big lock into several finer ones increases concurrency, but every extra mutex is another edge in the lock-order graph.

The most dangerous thing to do under a lock is to call code you did not write: a callback, a virtual function, a signal or observer list. That code might take a lock of its own, which creates a lock-order cycle you cannot see, or call back into your object and relock a non-recursive mutex. Copy what the callback needs while holding the lock, unlock, then call.

```cpp
#include <functional>
#include <mutex>
#include <vector>

class Notifier {
  std::mutex m_;
  std::vector<std::function<void(int)>> listeners_;
public:
  void publish(int v) {
    std::vector<std::function<void(int)>> copy;
    {
      std::lock_guard lk(m_);
      copy = listeners_;      // snapshot under the lock
    }
    for (auto& f : copy) f(v);   // unknown code runs with no lock held
  }
};
```

The same reasoning rules out returning a pointer or reference to guarded data from a locked accessor. Once the lock is released, the caller holds a path into the data that no mutex protects.

## What to remember

- Each `unlock` synchronizes with the next `lock` of the same mutex; that is what makes guarded non-atomic data race-free.
- Lockable types are defined by requirements: *BasicLockable* (`lock`, `unlock`), *Lockable* (adds `try_lock`), *TimedLockable* (adds timed tries).
- `try_lock` may fail spuriously, and a failed `try_lock` synchronizes with nothing.
- `std::mutex` has a `constexpr` constructor. Mutexes are neither copyable nor movable.
- Prefer `scoped_lock`; use `unique_lock` when you need to unlock early, move ownership, or wait on a condition variable; use `shared_lock` for readers.
- A lock wrapper that is a temporary, or a parenthesized declaration, protects nothing.
- `std::lock` and multi-mutex `scoped_lock` avoid deadlock among their arguments; the algorithm is unspecified.
- Relocking a non-recursive mutex, unlocking one you do not own, destroying one that is owned, and exiting a thread while owning one are all undefined behavior.
- Block-scope static initialization is thread-safe since C++11, retries after an exception, and is undefined if it recurses.
- `call_once` retries after an exceptional execution and synchronizes the returning execution with all passive calls.
- Never call unknown code while holding a lock. Snapshot, unlock, then call.

## Concept Map Outline

- **Mutexes and locks:** A mutex makes critical sections exclusive, and each unlock synchronizes with the next lock.
  - **Mutex kinds:** All are neither copyable nor movable; their identity is what threads agree on.
    - **std::mutex:** Plain exclusive mutex with a constexpr constructor, so globals are constant-initialized.
    - **recursive_mutex:** The owner may relock; unlock as many times; exceeding the unspecified depth throws.
    - **Timed mutexes:** timed_mutex and recursive_timed_mutex add try_lock_for and try_lock_until.
    - **Shared mutexes:** shared_mutex (C++17) allows many lock_shared holders or one exclusive owner; no upgrade.
    - **Spurious try_lock:** try_lock may fail on a free mutex, and a failed try_lock synchronizes with nothing.
  - **Lock wrappers:** RAII types that tie ownership to a scope, satisfying the Lockable requirements on the inside.
    - **lock_guard:** Locks in the constructor, unlocks in the destructor; not movable; adopt_lock takes over.
    - **scoped_lock (C++17):** Variadic; with several mutexes it uses the std::lock algorithm.
    - **unique_lock:** Movable, optional ownership, defer_lock and try_to_lock; required by condition_variable.
    - **shared_lock (C++14):** Calls lock_shared and unlock_shared, for readers of a shared mutex.
    - **Unnamed wrappers:** scoped_lock{m}; unlocks at once; unique_lock<mutex>(m); declares a new variable m.
  - **Deadlock:** A cycle of threads each holding a mutex the next one wants.
    - **Lock ordering:** A global acquisition order makes cycles impossible.
    - **std::lock:** Locks several Lockables without deadlock by an unspecified algorithm; unlocks all on exception.
    - **std::try_lock:** Returns -1 on success, or the zero-based index of the first mutex it could not lock.
  - **Undefined behavior:** Mutex rules are preconditions, so breaking them is undefined, not an error code.
    - **Relocking:** Locking a non-recursive mutex the thread already owns; deadlock is common, not guaranteed.
    - **Foreign unlock:** Only the owning thread may unlock a mutex.
    - **Owned at death:** Destroying an owned mutex, or a thread ending while it owns one.
  - **One-time initialization:** Two standard ways to run initialization exactly once under concurrency.
    - **Magic statics:** Since C++11 concurrent callers wait; a throw means retry; recursive re-entry is undefined.
    - **call_once:** Exceptional executions leave the flag unset; the returning one synchronizes with passive calls.
  - **Granularity:** Hold a lock for the shortest stretch that keeps the invariant intact.
    - **No unknown code:** Callbacks under a lock can relock or invert lock order; snapshot, unlock, then call.
    - **No leaked references:** A reference to guarded data returned from a locked accessor is unprotected afterwards.

## Standardese Quiz Questions

### Question 1 [warmup] ([thread.mutex.requirements.mutex], [thread.mutex.class])

What does the standard say about calling `f()`?

```cpp
#include <mutex>

std::mutex m;

void g() { std::lock_guard lk(m); }
void f() { std::lock_guard lk(m); g(); }

int main() { f(); }
```

A. It deadlocks, guaranteed
B. It works: a thread may relock a mutex it already owns
C. `g` throws `std::system_error` with `resource_deadlock_would_occur`
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** For `std::mutex`, the calling thread not owning the mutex is a precondition of `lock`, so the second lock in `g` is undefined behavior. Deadlock is the common outcome and a note allows an implementation that detects it to report `resource_deadlock_would_occur`, but neither is guaranteed, which is why the first and third options are wrong. Only the recursive mutex types allow the owner to lock again.

### Question 2 [warmup] ([thread.lock.unique])

In C++17 or later, what does this program print?

```cpp
#include <iostream>
#include <mutex>

std::mutex m;

int main() {
  std::unique_lock lk(m, std::defer_lock);
  std::cout << lk.owns_lock();
  lk.lock();
  std::cout << lk.owns_lock() << '\n';
}
```

A. `11`
B. `01`
C. `00`
D. Nothing; `lk.lock()` deadlocks because the constructor already locked `m`

**Answer (B):** `01`

**Why:** `std::defer_lock` associates the `unique_lock` with the mutex without locking it, so `owns_lock()` is false at first. The explicit `lk.lock()` then acquires `m`, and the destructor unlocks it at the end of `main`. The deadlock option assumes every `unique_lock` constructor locks, which is only true for the untagged one.

### Question 3 [warmup] ([thread.lock.scoped], [thread.lock.algorithm])

What does this program print?

```cpp
#include <cstdio>
#include <mutex>
#include <thread>

std::mutex a, b;
long n = 0;

void forward() {
  for (int i = 0; i < 100000; ++i) {
    std::scoped_lock lk(a, b);
    ++n;
  }
}

void backward() {
  for (int i = 0; i < 100000; ++i) {
    std::scoped_lock lk(b, a);
    ++n;
  }
}

int main() {
  std::thread t1(forward), t2(backward);
  t1.join();
  t2.join();
  std::printf("%ld\n", n);
}
```

A. It may deadlock, because the two threads take the mutexes in opposite orders
B. Some value up to 200000, because `++n` is not atomic
C. `200000`
D. Ill-formed: `scoped_lock` arguments must be listed in a consistent order

**Answer (C):** `200000`

**Why:** With more than one mutex, `scoped_lock` acquires them using the `std::lock` algorithm, which avoids deadlock whatever order the arguments are given in. Every `++n` happens while holding both mutexes, so the increments are serialized and ordered by unlock-to-lock synchronization, and no update is lost. Opposite-order deadlock is exactly the problem `std::lock` exists to solve; it would be the right answer with two nested `lock_guard`s.

### Question 4 [tricky] ([stmt.ambig], [dcl.ambig.res], [thread.lock.unique])

What does the first statement of `bump` do?

```cpp
#include <mutex>

std::mutex m;
int counter = 0;

void bump() {
  std::unique_lock<std::mutex>(m);
  ++counter;
}
```

A. Locks `m` until the end of `bump`
B. Declares a default-constructed `unique_lock` named `m`, so nothing is locked
C. Locks `m` and unlocks it again at the end of the statement
D. Nothing: it is ill-formed because `unique_lock` has no default constructor

**Answer (B):** Declares a default-constructed `unique_lock` named `m`, so nothing is locked

**Why:** A statement that can be read as a declaration is a declaration, and `T(m);` declares a variable `m` of type `T` with redundant parentheses. So it declares a new local `unique_lock` named `m` that shadows the mutex and owns nothing, and `++counter` runs unprotected. The third option describes `std::unique_lock<std::mutex>{m};`, which creates a temporary. `unique_lock` does have a default constructor; `lock_guard` does not, which is why the compiler rejects the same mistake with `lock_guard`.

### Question 5 [tricky] ([thread.mutex.requirements.mutex])

No other thread exists. What does the standard guarantee this program prints?

```cpp
#include <cstdio>
#include <mutex>

std::mutex m;

int main() {
  if (m.try_lock()) {
    std::puts("locked");
    m.unlock();
  } else {
    std::puts("not locked");
  }
}
```

A. `locked`, because the mutex is free
B. `not locked`, because `try_lock` on a static mutex fails before `main`
C. Undefined behavior, because `try_lock` needs a `unique_lock`
D. Either `locked` or `not locked`

**Answer (D):** Either `locked` or `not locked`

**Why:** [thread.mutex.requirements.mutex] allows `try_lock` to fail to obtain the lock even when no thread owns the mutex. Implementations do this rarely, and on a quiet mutex you will practically always see `locked`, but the standard does not promise it. That is the reason a failed `try_lock` must never be read as evidence that another thread holds the lock.

### Question 6 [tricky] ([thread.once.callonce])

According to the standard, what does this program print?

```cpp
#include <iostream>
#include <mutex>

std::once_flag flag;
int calls = 0;

void init() {
  ++calls;
  if (calls == 1) throw 1;
}

int main() {
  for (int i = 0; i < 3; ++i) {
    try {
      std::call_once(flag, init);
    } catch (int) {
    }
  }
  std::cout << calls << '\n';
}
```

A. `1`: the flag is set once `init` has been called, even if it threw
B. `2`
C. `3`: an exception makes the flag unusable, so every call runs `init`
D. Undefined behavior: the callable of `call_once` must not throw

**Answer (B):** `2`

**Why:** The first call is an exceptional execution: the exception propagates and the flag is not set. The second call is then an active execution that returns normally, which makes it the returning execution and sets the flag, so the third call is passive and does not run `init`. Throwing is explicitly allowed. Be aware that libstdc++ on targets that implement `call_once` with `pthread_once` has a long-standing bug here: on this page's macOS test machine the GCC build was killed instead of printing, while the Clang build with libc++ printed `2`.

### Question 7 [standardese] ([stmt.dcl])

What does the standard say about calling `f(0)`?

```cpp
int f(int n) {
  static int cached = f(n + 1);
  return cached + n;
}

int main() { return f(0); }
```

A. Undefined behavior
B. It returns 1, because `cached` is zero-initialized when the recursive call reads it
C. It is guaranteed to deadlock, because the static's guard waits for itself
D. It throws an exception reporting recursive initialization

**Answer (A):** Undefined behavior

**Why:** [stmt.dcl] says that if control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined. Deadlocking and throwing are both things real implementations do, but neither is required. The zero-initialized reading would be the answer only if recursion simply skipped the initializer, which the standard does not say.

### Question 8 [standardese] ([thread.mutex.class])

What does the standard say about this program?

```cpp
#include <mutex>
#include <thread>

std::mutex m;

int main() {
  std::thread t([] { m.lock(); });
  t.join();
}
```

A. It is fine: the mutex is unlocked automatically when its owner exits
B. It is fine as long as no other thread tries to lock `m`
C. Undefined behavior
D. It is ill-formed, because `m.lock()` without a lock wrapper is not allowed

**Answer (C):** Undefined behavior

**Why:** [thread.mutex.class] says the behavior is undefined if a thread terminates while owning a mutex, and also if a mutex owned by any thread is destroyed, which would happen later when `m` is destroyed at program exit. Nothing unlocks a mutex when its owner ends, which rules out the first option, and the undefined behavior does not depend on whether anyone else contends. Calling `lock` directly is legal; the wrappers are a convenience.

# Condition variables and waiting

> A condition variable lets a thread sleep until some state guarded by a mutex changes, and it is only correct when the waiter rechecks a predicate and the notifier changes that predicate under the mutex. C++20 adds atomic waits, semaphores, latches and barriers for the cases a condition variable handles clumsily.

- **Source:** C++ Atlas (https://cppatlas.com/topics/condition-variables-and-waiting)
- **Track:** Concurrency
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [thread.condition] (https://eel.is/c++draft/thread.condition), [thread.condition.condvar] (https://eel.is/c++draft/thread.condition.condvar), [thread.condition.condvarany] (https://eel.is/c++draft/thread.condition.condvarany), [thread.condvarany.intwait] (https://eel.is/c++draft/thread.condvarany.intwait), [thread.req.timing] (https://eel.is/c++draft/thread.req.timing), [atomics.wait] (https://eel.is/c++draft/atomics.wait), [thread.sema] (https://eel.is/c++draft/thread.sema), [thread.latch] (https://eel.is/c++draft/thread.latch), [thread.barrier] (https://eel.is/c++draft/thread.barrier)
- **cppreference links:** [std::condition_variable](https://en.cppreference.com/w/cpp/thread/condition_variable), [std::condition_variable::wait](https://en.cppreference.com/w/cpp/thread/condition_variable/wait), [std::condition_variable_any::wait](https://en.cppreference.com/w/cpp/thread/condition_variable_any/wait), [std::condition_variable::wait_for](https://en.cppreference.com/w/cpp/thread/condition_variable/wait_for), [std::atomic<T>::wait](https://en.cppreference.com/w/cpp/atomic/atomic/wait), [std::counting_semaphore, std::binary_semaphore](https://en.cppreference.com/w/cpp/thread/counting_semaphore), [std::latch](https://en.cppreference.com/w/cpp/thread/latch), [std::barrier](https://en.cppreference.com/w/cpp/thread/barrier)
- **Prerequisites:** mutexes-and-locks, threads-and-jthread, atomics-and-memory-ordering, chrono

## The one idea

A condition variable does not hold a condition. It holds a queue of sleeping threads, and a notification is a nudge that says "something may have changed, go and look". Notifications are not stored: notifying a condition variable that nobody is waiting on does nothing at all. The condition itself is ordinary state, the *predicate*, guarded by a mutex, and the only correct way to use a condition variable is to check the predicate under that mutex, sleep if it is false, and check again on every wake.

> **Mental model.** The mutex protects the predicate, the predicate is the truth, and the condition variable is just an efficient way to sleep between checks. If your code would still be correct with `wait` replaced by "unlock, yield, relock", it is correct with `wait`.

## What wait actually does

`std::condition_variable::wait(lock)` takes a `std::unique_lock<std::mutex>` that the caller holds. It atomically releases the mutex and blocks. When it is unblocked, it reacquires the mutex before returning, so the caller always holds the lock again afterwards. Unblocking happens on `notify_one`, `notify_all`, or *spuriously*, for no reason at all. The standard permits spurious wakeups because some platforms' native primitives have them and because they make the implementation simpler.

The overload that takes a predicate, `wait(lock, pred)`, is exactly `while (!pred()) wait(lock);`. It checks before the first sleep, so if the predicate is already true, it returns without blocking and without needing any notification. Use it everywhere; the bare overload is a building block.

```cpp
#include <condition_variable>
#include <mutex>
#include <queue>

class Channel {
  std::mutex m_;
  std::condition_variable cv_;
  std::queue<int> q_;
public:
  void push(int v) {
    { std::lock_guard lk(m_); q_.push(v); }   // change the predicate under the mutex
    cv_.notify_one();
  }
  int pop() {
    std::unique_lock lk(m_);
    cv_.wait(lk, [&] { return !q_.empty(); });   // loop handles spurious wakeups
    int v = q_.front();
    q_.pop();
    return v;
  }
};
```

`std::condition_variable` accepts only `std::unique_lock<std::mutex>`, which lets implementations map it directly onto the platform's primitive. A `lock_guard` cannot be passed, because `wait` must unlock and relock it. All threads waiting on one condition variable at the same time must use the same mutex.

> **Standardese.** [thread.condition.condvar] makes it a precondition of `wait` that the lock is owned by the calling thread and that every concurrently waiting thread supplied the same mutex. It also says that if `wait` cannot reacquire the lock, `std::terminate` is called. [thread.condition] requires notifications and the parts of each wait to behave as if they happen in a single total order consistent with happens-before.

## Lost wakeups, and why the predicate needs the mutex

The atomic unlock-and-block step exists to close one gap: between the waiter's check of the predicate and its going to sleep, nobody may slip in a change and a notification. That guarantee only works if the notifier changes the predicate while holding the same mutex. Making the flag atomic is not a substitute.

```cpp
#include <atomic>
#include <condition_variable>
#include <mutex>

std::mutex m;
std::condition_variable cv;
std::atomic<bool> ready{false};

void waiter() {
  std::unique_lock lk(m);
  cv.wait(lk, [] { return ready.load(); });   // may sleep forever
}

void setter() {
  ready = true;      // not under m: no data race, but...
  cv.notify_one();   // ...this can land between waiter's check and its sleep
}
```

Here is the losing interleaving. The waiter takes the mutex and sees `ready == false`. Before it blocks, the setter stores `true` and notifies; nobody is waiting yet, so the notification evaporates. The waiter then blocks, and nothing will ever wake it. If the setter had locked `m` around the store, it could not have run between the check and the block, because the waiter holds `m` for that whole stretch. The lock can be released before `notify_one` is called; it only has to cover the change.

## Notify inside or outside the lock

Both placements are correct if the predicate was changed under the mutex. Notifying after unlocking avoids waking a thread that will immediately block again on the mutex the notifier still holds, though many implementations already avoid that cost. Notifying while still holding the lock has one real advantage: object lifetime.

The destructor of a condition variable requires that no thread is blocked on it, and of course nobody may call `notify_one` on a destroyed one. If the waiter owns the condition variable, it may see the predicate become true, return, and destroy the condition variable while the notifier is still about to call `notify_one`. Notifying under the lock prevents this, because the waiter cannot return from `wait` until it reacquires the mutex, which is after the notification has finished.

```cpp
#include <condition_variable>
#include <mutex>
#include <thread>

void run() {
  std::mutex m;
  std::condition_variable cv;
  bool done = false;
  std::thread([&] {
    std::lock_guard lk(m);
    done = true;
    cv.notify_one();   // under the lock: run() cannot return before this finishes
  }).detach();
  std::unique_lock lk(m);
  cv.wait(lk, [&] { return done; });
}   // cv and m are destroyed here
```

Move the `notify_one` after the lock is released and this function may destroy `cv` while the detached thread is still about to use it, which is undefined behavior. Detaching is rarely a good idea, as threads-and-jthread explains, but the same pattern appears whenever a waiter owns the synchronization object.

## condition_variable_any and stop tokens

`std::condition_variable_any` works with any *Cpp17BasicLockable*, such as a `std::shared_lock`, a `std::unique_lock` over a mutex type other than `std::mutex`, or your own type. It is usually somewhat heavier, since it may need an internal mutex of its own.

In C++20 it gained the only stop-aware waits in the library. `wait(lock, stoken, pred)` registers for the duration of the call to be woken when stop is requested on `stoken`, and then behaves as `while (!stoken.stop_requested()) { if (pred()) return true; wait(lock); } return pred();`. The result is the predicate's value, so a `false` return means "woken by a stop request, and the condition still does not hold". There are matching `wait_for` and `wait_until` overloads, all of which require a predicate.

```cpp
#include <condition_variable>
#include <mutex>
#include <queue>
#include <stop_token>
#include <thread>

std::mutex m;
std::condition_variable_any cv;
std::queue<int> jobs;

void worker(std::stop_token st) {
  while (true) {
    std::unique_lock lk(m);
    if (!cv.wait(lk, st, [] { return !jobs.empty(); }))
      return;                       // stop requested and no job is waiting
    jobs.pop();                     // ... process the job ...
  }
}

int main() {
  std::jthread t(worker);   // ~jthread requests stop, which wakes the wait
}
```

## Timed waits and clocks

`wait_until(lock, abs_time)` returns `std::cv_status::timeout` if the deadline has passed when it returns, and `no_timeout` otherwise, which includes spurious wakeups. `wait_for(lock, rel_time)` is specified as `wait_until(lock, std::chrono::steady_clock::now() + rel_time)`, so it measures elapsed time and is immune to someone changing the wall clock. A deadline expressed as a `system_clock` time point, by contrast, tracks adjustments to that clock. The clock types themselves belong to the chrono topic.

The predicate forms return `bool`, and on timeout they return the *predicate's value*, not `false`. A condition that became true just as the deadline expired is reported as success.

```cpp
#include <chrono>
#include <condition_variable>
#include <mutex>

std::mutex m;
std::condition_variable cv;
bool ready = false;

bool wait_ready() {
  std::unique_lock lk(m);
  // true if ready became true in time, or happened to be true at the deadline
  return cv.wait_for(lk, std::chrono::milliseconds(50), [] { return ready; });
}
```

[thread.req.timing] lets every timeout be late by an unspecified amount, for scheduling and resource reasons, so a timed wait is a lower bound on the delay, never an exact one.

## Lighter tools: atomic wait, semaphores, latches and barriers

C++20 added primitives that cover common patterns without a mutex.

`std::atomic<T>::wait(old)` blocks while the atomic's value equals `old`, and `notify_one` or `notify_all` wakes it. It is introduced in atomics-and-memory-ordering. Unlike a condition variable, it compares the value itself, so it returns at once if the value already differs and it never returns spuriously with the value unchanged. It can miss a change that is undone before it looks again, which is fine when you only wait for a value to move on.

`std::counting_semaphore<LeastMaxValue>` holds a counter. `acquire` blocks until the counter is positive and decrements it, `release(n)` adds `n`, and `try_acquire`, `try_acquire_for` and `try_acquire_until` are the non-blocking and timed forms; `try_acquire` is allowed to fail spuriously. A semaphore has no owner, so any thread may release it, which is exactly what a mutex forbids. `std::binary_semaphore` is `counting_semaphore<1>`. `max()` may be larger than the template argument, but releasing past `max()` is undefined behavior.

```cpp
#include <semaphore>

std::counting_semaphore<4> slots(4);   // at most four concurrent downloads

void download() {
  slots.acquire();
  // ... use one of the four slots ...
  slots.release();
}
```

`std::latch` is a single-use countdown. `count_down(n)` decrements, `wait` blocks until the count reaches zero, and `arrive_and_wait` does both. Decrementing below zero is undefined behavior, and a latch cannot be reset. Curiously, `try_wait` may return `false` "with very low probability" even after the count has reached zero.

`std::barrier<CompletionFunction>` is the reusable version, built around phases. Each participant calls `arrive_and_wait`; when the expected number have arrived, the completion function runs once on one of the arriving threads, and then everyone is released into the next phase. `arrive_and_drop` arrives and removes the caller from future phases. The completion function must be callable without throwing.

```cpp
#include <barrier>
#include <cstdio>
#include <thread>
#include <vector>

int main() {
  int phase = 0;
  std::barrier sync(3, [&]() noexcept { std::printf("phase %d done\n", ++phase); });
  std::vector<std::jthread> workers;
  for (int i = 0; i < 3; ++i)
    workers.emplace_back([&] {
      for (int step = 0; step < 2; ++step) {
        // ... this thread's share of the step ...
        sync.arrive_and_wait();   // nobody starts the next step until all finish
      }
    });
}   // prints "phase 1 done", then "phase 2 done"
```

> **Pitfall.** These primitives synchronize, but they do not protect data. A barrier orders the steps of different threads; it does not make two threads writing the same object inside one step race-free. Each still needs its own discipline: disjoint data or a mutex.

## Choosing a tool

- Waiting for arbitrary state guarded by a mutex: `condition_variable` with a predicate.
- The same, but with a non-`unique_lock` lock or with stop-token cancellation: `condition_variable_any`.
- Waiting for one atomic value to change: `atomic::wait` and `notify`.
- Limiting concurrency, or signalling between threads with no ownership: `counting_semaphore`.
- One-shot "everyone is ready" or "all work is done": `latch`.
- Repeated lock-step phases among a fixed group: `barrier`.
- Waiting for a single result, possibly an exception: a future, covered in futures-promises-and-async.

## What to remember

- Notifications are not remembered. A notify with no waiter does nothing.
- `wait` atomically unlocks and blocks, reacquires before returning, and may wake spuriously. Always use the predicate form.
- Change the predicate while holding the mutex, even if it is atomic; otherwise the wakeup can be lost.
- Notifying inside or outside the lock is correct; inside also protects a condition variable whose owner may destroy it on return.
- All concurrent waiters on one condition variable must use the same mutex.
- `condition_variable_any` takes any lockable and, since C++20, stop tokens; its stop-aware waits return the predicate's value.
- `wait_for` measures with `steady_clock`. Timed predicate waits return the predicate on timeout, and every timeout may be late.
- `atomic::wait` compares values and never returns spuriously with an unchanged value.
- Semaphores have no owner; latches are single-use; barriers repeat by phase and run a `noexcept` completion step.

## Concept Map Outline

- **Condition variables and waiting:** Sleep until mutex-guarded state changes, rechecking a predicate on every wake; C++20 adds lighter primitives.
  - **wait semantics:** Atomically unlock and block, then relock before returning.
    - **Spurious wakeups:** wait may return without any notify, so the predicate must be rechecked.
    - **Predicate overload:** wait(lock, pred) is while (!pred()) wait(lock); it returns at once if pred is true.
    - **unique_lock only:** condition_variable takes unique_lock<mutex>; a lock_guard cannot be unlocked by wait.
    - **One mutex:** All threads waiting at the same time must pass the same mutex, or behavior is undefined.
  - **Notification:** A notify is a nudge, never stored; with no waiter it does nothing.
    - **Lost wakeup:** Changing the predicate without the mutex lets a notify land between check and sleep.
    - **Atomic is not enough:** An atomic flag avoids a data race but not the lost wakeup; take the mutex to change it.
    - **Notify under lock:** Correct either way; under the lock also keeps a waiter from destroying the cv too early.
  - **condition_variable_any:** Works with any BasicLockable, such as shared_lock, at some extra cost.
    - **Stop-aware waits:** C++20 wait(lock, stoken, pred) wakes on stop requests and returns pred().
    - **False means stopped:** A false result means stop was requested while the predicate still did not hold.
  - **Timed waits:** wait_for and wait_until bound the sleep; timeouts may always be late.
    - **cv_status:** Bare timed waits return timeout or no_timeout; no_timeout includes spurious wakes.
    - **Predicate on timeout:** Predicate forms return the predicate's value at the deadline, not simply false.
    - **Clocks:** wait_for uses steady_clock; a system_clock deadline follows wall-clock adjustments.
  - **C++20 primitives:** Mutex-free tools for patterns a condition variable expresses clumsily.
    - **atomic::wait:** Blocks while the value equals old; returns at once if it differs; never spuriously unchanged.
    - **counting_semaphore:** acquire and release a counter; no owner, so any thread may release.
    - **latch:** Single-use countdown; going below zero is undefined; try_wait may rarely report false.
    - **barrier:** Reusable phases; a noexcept completion step runs once per phase on an arriving thread.
  - **Choosing:** Pick the narrowest primitive that expresses the wait.
    - **Arbitrary state:** Use a condition_variable with a predicate under the guarding mutex.
    - **One result:** Use a future when waiting for a single value or exception.

## Standardese Quiz Questions

### Question 1 [warmup] ([thread.condition.condvar])

What does this program do?

```cpp
#include <condition_variable>
#include <cstdio>
#include <mutex>

std::mutex m;
std::condition_variable cv;
bool ready = true;

int main() {
  std::unique_lock lk(m);
  cv.wait(lk, [] { return ready; });
  std::puts("done");
}
```

A. Blocks forever, because nothing ever calls `notify_one`
B. Prints `done` unless a spurious wakeup is missed
C. Undefined behavior: `wait` requires a matching notification
D. Prints `done`

**Answer (D):** Prints `done`

**Why:** `wait(lock, pred)` is specified as `while (!pred()) wait(lock);`, so the predicate is checked before the first sleep. It is already true, so `wait` returns at once without blocking. The first option is what the bare `wait(lock)` overload would do here, which is one more reason to always pass a predicate.

### Question 2 [warmup] ([thread.condition.condvar])

Is this code well-formed?

```cpp
#include <condition_variable>
#include <mutex>

std::mutex m;
std::condition_variable cv;
bool ready = false;

void waiter() {
  std::lock_guard<std::mutex> lk(m);
  cv.wait(lk, [] { return ready; });
}
```

A. Well-formed: any lock that holds `m` can be passed
B. Ill-formed: `std::condition_variable::wait` takes only `std::unique_lock<std::mutex>`
C. Well-formed, but undefined behavior because `lock_guard` cannot be unlocked
D. Ill-formed: the predicate must be a function pointer

**Answer (B):** Ill-formed: `std::condition_variable::wait` takes only `std::unique_lock<std::mutex>`

**Why:** Every `wait` overload of `std::condition_variable` takes a `std::unique_lock<std::mutex>&`, because the wait must unlock and relock it, and `lock_guard` offers neither operation. There is no conversion, so overload resolution fails and the code does not compile. `std::condition_variable_any` accepts any lockable type, but a `lock_guard` still lacks `lock` and `unlock`, so it would not work there either.

### Question 3 [warmup] ([thread.sema.cnt])

In C++20, what does this program print?

```cpp
#include <cstdio>
#include <semaphore>
#include <thread>

std::binary_semaphore sem(0);

int main() {
  std::thread t([] {
    std::puts("worker");
    sem.release();
  });
  sem.acquire();
  std::puts("main");
  t.join();
}
```

A. `worker` then `main`
B. `main` then `worker`, or the other way round
C. Undefined behavior: only the thread that acquired a semaphore may release it
D. Nothing: `acquire` blocks forever because the count starts at 0

**Answer (A):** `worker` then `main`

**Why:** The semaphore starts at 0, so `acquire` blocks until the worker's `release` makes it 1. A release strongly happens before an acquire that observes its effect, so the worker's `puts` comes first. Semaphores have no notion of ownership, unlike mutexes, so releasing from a different thread is the normal use, not undefined behavior.

### Question 4 [tricky] ([thread.condition.condvar], [thread.condition], [intro.races])

`waiter` and `setter` run concurrently in two threads, once each. Which statement is correct?

```cpp
#include <atomic>
#include <condition_variable>
#include <mutex>

std::mutex m;
std::condition_variable cv;
std::atomic<bool> ready{false};

void waiter() {
  std::unique_lock lk(m);
  cv.wait(lk, [] { return ready.load(); });
}

void setter() {
  ready = true;
  cv.notify_one();
}
```

A. Correct: the flag is atomic, so the waiter always wakes
B. Undefined behavior: data race on `ready`
C. No data race, but `waiter` can block forever
D. Correct, provided `notify_all` is used instead of `notify_one`

**Answer (C):** No data race, but `waiter` can block forever

**Why:** All accesses to `ready` are atomic, so there is no data race. But the setter does not take `m`, so it can store and notify after the waiter has checked the predicate and before it blocks; that notification finds no waiter and is lost, and the waiter then sleeps forever. Locking `m` around the store closes the window, because the waiter holds `m` from its check until the atomic unlock-and-block. `notify_all` loses the same race.

### Question 5 [tricky] ([atomics.wait], [atomics.types.operations])

In C++20, what does this program do?

```cpp
#include <atomic>
#include <cstdio>

int main() {
  std::atomic<int> a{1};
  a.wait(0);
  std::puts("returned");
}
```

A. Prints `returned`
B. Blocks forever, because nothing calls `notify_one`
C. Blocks until a spurious wakeup, then prints `returned`
D. Undefined behavior: `wait` needs a matching `notify`

**Answer (A):** Prints `returned`

**Why:** `a.wait(old)` blocks only while the value equals `old`: it loads, compares, and returns as soon as the values differ. The value is 1 and `old` is 0, so it returns at once. The tempting answer treats `wait` like a condition variable that sleeps until notified; the argument is the value you expect to change away from, not a value to wait for.

### Question 6 [tricky] ([thread.condition.condvar], [basic.life])

Which statement about `run` is correct?

```cpp
#include <condition_variable>
#include <mutex>
#include <thread>

void run() {
  std::mutex m;
  std::condition_variable cv;
  bool done = false;
  std::thread([&] {
    {
      std::lock_guard lk(m);
      done = true;
    }
    cv.notify_one();
  }).detach();
  std::unique_lock lk(m);
  cv.wait(lk, [&] { return done; });
}
```

A. It is correct: `done` is changed under the mutex, so nothing can go wrong
B. It can deadlock, because the notification may be lost
C. It is ill-formed: a detached thread cannot capture locals by reference
D. It can have undefined behavior: `run` may return and destroy `cv` before the worker calls `notify_one`

**Answer (D):** It can have undefined behavior: `run` may return and destroy `cv` before the worker calls `notify_one`

**Why:** The predicate is changed under the mutex, so no wakeup is lost; the waiter either sees `done` or is already blocked when the notification arrives. The problem is lifetime: after the worker unlocks, `run` may see `done`, for instance through a spurious wakeup or before ever blocking, return, and destroy `cv` while the worker is still about to call `notify_one` on it. Calling `notify_one` before the lock is released prevents this, because `run` cannot return from `wait` until it reacquires `m`.

### Question 7 [standardese] ([thread.condition.condvar])

Threads running `a` and `b` are both blocked on `cv` at the same time. What does the standard say?

```cpp
#include <atomic>
#include <condition_variable>
#include <mutex>

std::condition_variable cv;
std::mutex m1, m2;
std::atomic<bool> ready{false};

void a() {
  std::unique_lock lk(m1);
  cv.wait(lk, [] { return ready.load(); });
}

void b() {
  std::unique_lock lk(m2);
  cv.wait(lk, [] { return ready.load(); });
}
```

A. It is fine: each waiter reacquires its own mutex on wakeup
B. It is fine, but only `notify_all` is guaranteed to wake both
C. Undefined behavior: concurrent waiters must all use the same mutex
D. Ill-formed: a condition variable is bound to one mutex at construction

**Answer (C):** Undefined behavior: concurrent waiters must all use the same mutex

**Why:** A precondition of `std::condition_variable::wait` is that either no other thread is waiting on the object, or every concurrently waiting thread passed a lock on the same mutex. Two waiters with `m1` and `m2` violate it, so the behavior is undefined. Nothing binds the mutex at construction, which is why the code compiles; the constraint is on how waits overlap at run time. Using different mutexes at different, non-overlapping times is allowed.

### Question 8 [standardese] ([thread.condvarany.intwait])

In C++20, what does this program print?

```cpp
#include <condition_variable>
#include <cstdio>
#include <mutex>
#include <stop_token>

int main() {
  std::mutex m;
  std::condition_variable_any cv;
  std::stop_source src;
  src.request_stop();
  std::unique_lock lk(m);
  bool r = cv.wait(lk, src.get_token(), [] { return false; });
  std::printf("%d\n", r);
}
```

A. `1`, because the wait ended without a timeout
B. `0`
C. Nothing: it blocks forever, because nobody notifies `cv`
D. Nothing: a stop request makes the wait throw

**Answer (B):** `0`

**Why:** The stop-aware `wait` is specified as `while (!stoken.stop_requested()) { if (pred()) return true; wait(lock); } return pred();`. Stop was already requested, so the loop body never runs and the function returns `pred()`, which is `false`. The result always reports the predicate, so a `false` return means stop was requested while the condition still did not hold. Nothing is thrown, and no notification is needed.

# Futures, promises and async

> A future and its provider share one heap-allocated state that carries exactly one value or exception from one thread to another. This page covers promise, packaged_task and std::async, the launch-policy and destructor traps, the future_error cases, and why standard futures cannot be chained.

- **Source:** C++ Atlas (https://cppatlas.com/topics/futures-promises-and-async)
- **Track:** Concurrency
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [futures.state] (https://eel.is/c++draft/futures.state), [futures.errors] (https://eel.is/c++draft/futures.errors), [futures.future.error] (https://eel.is/c++draft/futures.future.error), [futures.promise] (https://eel.is/c++draft/futures.promise), [futures.unique.future] (https://eel.is/c++draft/futures.unique.future), [futures.shared.future] (https://eel.is/c++draft/futures.shared.future), [futures.async] (https://eel.is/c++draft/futures.async), [futures.task] (https://eel.is/c++draft/futures.task)
- **cppreference links:** [std::future](https://en.cppreference.com/w/cpp/thread/future), [std::promise](https://en.cppreference.com/w/cpp/thread/promise), [std::shared_future](https://en.cppreference.com/w/cpp/thread/shared_future), [std::packaged_task](https://en.cppreference.com/w/cpp/thread/packaged_task), [std::async](https://en.cppreference.com/w/cpp/thread/async), [std::launch](https://en.cppreference.com/w/cpp/thread/launch), [std::future_errc](https://en.cppreference.com/w/cpp/thread/future_errc), [std::future::get](https://en.cppreference.com/w/cpp/thread/future/get)
- **Prerequisites:** threads-and-jthread, condition-variables-and-waiting, exceptions-and-stack-unwinding, copy-and-move

## The one idea

Every future-based handoff is built on one object you never name: the *shared state*. It is allocated by the producer side, and it holds a slot for either a value or an exception, a "ready" flag, and sometimes a deferred function waiting to run. The producer side is an *asynchronous provider*: a `std::promise`, a `std::packaged_task`, or the machinery behind `std::async`. The consumer side is an *asynchronous return object*: a `std::future` or a `std::shared_future`. Both sides hold references to the same shared state, and it is destroyed when the last reference is released.

Making the state ready synchronizes with whoever observes that it is ready, through `wait` or `get`. So a value set through a promise, and everything the producer wrote before setting it, is visible to the thread that gets it, with no extra locking.

> **Mental model.** A promise and its future are the two ends of a one-shot pipe that carries exactly one thing, a value or an exception. Each end can be used once, and if the sending end is dropped without sending, the pipe delivers a "broken promise" error instead.

## promise and future

A `std::promise<T>` creates the shared state. `get_future()` hands out the matching `std::future<T>`, and `set_value` or `set_exception` makes the state ready. In another thread, `future::get()` blocks until the state is ready and then returns the value or rethrows the exception.

```cpp
#include <future>
#include <thread>

int main() {
  std::promise<int> p;
  std::future<int> f = p.get_future();
  std::thread t([&p] { p.set_value(42); });   // the producer
  int v = f.get();                            // blocks until ready, then 42
  t.join();
  return v == 42 ? 0 : 1;
}
```

Each operation has a single-use rule, and breaking one throws `std::future_error`, whose `code()` compares equal to a `std::future_errc` value:

- calling `get_future()` a second time gives `future_already_retrieved`;
- setting a value or exception a second time gives `promise_already_satisfied`;
- using a promise that has no shared state, for example a moved-from one, gives `no_state`;
- destroying a promise whose state is not ready *abandons* the state: the promise stores a `future_error` with `broken_promise` and makes the state ready, so the waiting `get()` throws it instead of blocking forever.

```cpp
#include <future>
#include <iostream>

int main() {
  std::future<int> f;
  {
    std::promise<int> p;
    f = p.get_future();
  }   // p abandons the shared state here
  try {
    f.get();
  } catch (const std::future_error& e) {
    std::cout << (e.code() == std::future_errc::broken_promise) << '\n';   // 1
  }
}
```

`set_value_at_thread_exit` and `set_exception_at_thread_exit` store the result immediately but delay making the state ready until the current thread has destroyed its `thread_local` objects. They are the safe way to signal completion from a detached thread.

## get moves the value out, and then the future is empty

`std::future<T>::get()` is a one-time operation. It waits, then *moves* the value out of the shared state and releases the state, after which `valid()` is false. That is why `future<std::unique_ptr<T>>` works. The reference form `future<T&>` returns the reference, and `future<void>` returns nothing.

Calling `get`, or any member other than the destructor, move assignment, `share` and `valid`, on a future whose `valid()` is false is undefined behavior. The standard recommends that implementations throw `future_error` with `no_state` in that case, and libstdc++ does, but code must not rely on it.

> **Standardese.** [futures.unique.future] says that calling any member function other than the destructor, the move-assignment operator, `share` or `valid` on a `future` whose `valid() == false` is undefined, and adds as recommended practice that implementations detect this and throw `future_error` with `no_state`.

When several consumers need the result, call `share()` to convert the future into a `std::shared_future<T>`. A shared future is copyable, and its `get()` returns `const T&` and leaves the value in place, so it can be called any number of times. Give each thread its own copy of the `shared_future` rather than sharing one object between threads. If the state holds an exception, every `get()` rethrows the stored exception.

```cpp
#include <future>
#include <memory>

int main() {
  std::promise<std::unique_ptr<int>> p;
  std::future<std::unique_ptr<int>> f = p.get_future();
  p.set_value(std::make_unique<int>(3));
  std::unique_ptr<int> v = f.get();   // moved out; f.valid() is now false

  std::promise<int> q;
  std::shared_future<int> s = q.get_future().share();
  q.set_value(9);
  const int& a = s.get();
  const int& b = s.get();             // same object, still there: &a == &b
  return *v + a - b;
}
```

## packaged_task: a callable that fills a promise

`std::packaged_task<R(Args...)>` wraps a callable together with a shared state. Calling the task runs the callable and stores its return value, or the exception it throws, in the state. Like a promise, it hands out exactly one future. It is move-only, so it can be pushed into a work queue as `std::move(task)`, and a type-erasing wrapper that accepts move-only callables, such as C++23's `std::move_only_function`, can hold it.

Calling the task a second time throws `future_error` with `promise_already_satisfied`, because the state is already ready. `reset()` abandons the old state and creates a fresh one, so the task can run again with a new future. A task destroyed without ever being called abandons its state, and its future reports `broken_promise`.

```cpp
#include <future>
#include <thread>

int square(int x) { return x * x; }

int main() {
  std::packaged_task<int(int)> task(square);
  std::future<int> f = task.get_future();
  std::thread t(std::move(task), 7);   // the task runs on t and fills the state
  int r = f.get();                     // 49
  t.join();
  return r == 49 ? 0 : 1;
}
```

## std::async and its launch policies

`std::async(policy, f, args...)` decay-copies its arguments, as `std::thread` does, and returns a future for the result. The policy is a bitmask of `std::launch` values:

- `std::launch::async` runs the function as if on a new thread, with its own fresh `thread_local` objects. If no thread can be started, `async` throws `std::system_error` with `resource_unavailable_try_again`.
- `std::launch::deferred` stores the function in the shared state and runs nothing. The first call to `get` or `wait` on any future sharing that state runs it, synchronously, in the calling thread. If nobody ever asks, it never runs.
- Both bits, which is what you get when you omit the policy, let the implementation choose either one.

The default is a trap. Code written as if the work runs concurrently is not guaranteed to. Thread-local variables may belong to the calling thread, and a polling loop on `wait_for` can spin forever, because the timed waits never run a deferred function. They return `std::future_status::deferred` immediately instead.

```cpp
#include <chrono>
#include <future>

int main() {
  using namespace std::chrono_literals;
  auto f = std::async([] { return 42; });   // policy: async | deferred
  // while (f.wait_for(10ms) != std::future_status::ready) {}
  //   ^ never ends if the implementation chose deferred
  if (f.wait_for(0s) == std::future_status::deferred) {
    // nothing is running; get() below will run the function right here
  }
  return f.get();
}
```

If you need concurrency, say `std::launch::async`. If you want lazy evaluation, say `std::launch::deferred`. Leave the choice to the implementation only when you truly do not care.

## The blocking destructor of async futures

When `std::async` launches a thread, the standard requires that the thread's completion synchronize with the return of the first function that detects the state is ready or of the last function that releases the state, whichever comes first. In practice that means the destructor of the last future referring to such a state blocks until the task finishes. No other future does this: a future from a `promise` or a `packaged_task` releases its state without waiting.

The consequence is easy to miss when the future is a temporary:

```cpp
#include <chrono>
#include <cstdio>
#include <future>
#include <thread>

int main() {
  (void)std::async(std::launch::async, [] {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    std::puts("a");
  });   // the temporary future's destructor waits here
  (void)std::async(std::launch::async, [] { std::puts("b"); });
}   // always prints a, then b: the two calls run one after the other
```

Since C++20 `std::async` is marked `[[nodiscard]]`, so compilers warn about the discarded result. The cast to `void` above silences the warning but not the waiting. To run work in the background, keep the future alive for as long as you want concurrency.

> **Pitfall.** The blocking destructor makes `std::async` futures behave differently from all others, which matters to code that stores futures generically. A container of futures from `std::async` waits for every task when it is destroyed. The same container filled from promises does not.

## Why standard futures do not chain

A `std::future` has no way to say "when this is ready, run that". The only ways to consume it are to block in `get` or `wait`, or to poll with `wait_for`. Composing asynchronous steps therefore costs a thread blocked in `get` per step, or a polling loop. The Concurrency TS proposed `future::then`, `when_all` and `when_any` under `std::experimental`, but they were never adopted into the standard. The common criticisms were that they left unclear which thread runs a continuation, and that every step needed its own heap-allocated, synchronized shared state.

C++26 takes a different route with `std::execution`, the senders and receivers model. A sender describes work without starting it, adaptors such as `then` and `when_all` compose senders into larger ones, and a scheduler decides where each piece runs. That model is the subject of the senders-and-receivers topic. Futures remain the simple tool for a single result handed from one thread to another.

## What to remember

- Promise, packaged_task and async write a shared state; future and shared_future read it. Making the state ready synchronizes with the thread that observes it.
- Each promise allows one `get_future` and one result. Violations throw `future_error` with `future_already_retrieved` or `promise_already_satisfied`.
- A promise or packaged_task destroyed without a result stores `broken_promise`, so `get()` throws rather than hangs.
- Exceptions travel through the shared state; `get()` rethrows them in the consuming thread.
- `future::get()` moves the value out and invalidates the future. Using an invalid future is undefined; libstdc++ throws `no_state`.
- `shared_future` is copyable, returns `const T&`, and can be read many times; give each thread its own copy.
- `packaged_task` runs once per state; a second call throws `promise_already_satisfied`, and `reset()` starts over.
- The default `std::async` policy may defer the work; timed waits then return `future_status::deferred` and never run it.
- The last future from an `async` that launched a thread blocks in its destructor, so discarded results serialize.
- Standard futures cannot chain. C++26 senders replace continuation-style composition.

## Concept Map Outline

- **Futures, promises and async:** Providers and futures share one state that carries exactly one value or exception between threads.
  - **Shared state:** Holds a value or exception, a ready flag, and possibly a deferred function.
    - **Providers:** promise, packaged_task and std::async write the result into the state.
    - **Return objects:** future and shared_future read the result; the last reference destroys the state.
    - **Synchronization:** Making the state ready synchronizes with the wait or get that observes it.
  - **promise and future:** A one-shot pipe: one get_future, one result, one get.
    - **broken_promise:** A provider destroyed without a result stores this error, so get throws instead of hanging.
    - **Single-use errors:** future_already_retrieved for a second get_future; promise_already_satisfied for a second result.
    - **get moves out:** future<T>::get moves the value and releases the state; valid() is then false.
    - **Invalid future:** Using a future with valid() false is undefined; throwing no_state is only recommended.
    - **At thread exit:** set_value_at_thread_exit makes the state ready after thread_local objects are destroyed.
  - **shared_future:** Copyable view of the state for many consumers, made by future::share().
    - **Repeatable get:** get returns const T& and leaves the value in place; every get rethrows a stored exception.
    - **One copy per thread:** Give each thread its own shared_future object rather than sharing one.
  - **packaged_task:** A move-only callable that stores its result or exception in a shared state.
    - **Run once:** A second call throws promise_already_satisfied.
    - **reset:** Abandons the old state and creates a fresh one, which needs a new future.
  - **std::async:** Decay-copies arguments and returns a future for the function's result.
    - **launch::async:** Runs as if on a new thread; throws system_error if no thread can be started.
    - **launch::deferred:** Runs lazily in the thread that first calls get or wait; never if nobody asks.
    - **Default policy:** async | deferred lets the implementation choose; timed waits may return deferred forever.
    - **Blocking destructor:** The last future for a launched async state waits for the task, so discarded results serialize.
  - **No continuations:** Standard futures can only be blocked on or polled, never chained.
    - **Concurrency TS:** future::then, when_all and when_any stayed in std::experimental and were not adopted.
    - **C++26 senders:** std::execution composes work lazily with schedulers; see senders-and-receivers.

## Standardese Quiz Questions

### Question 1 [warmup] ([futures.promise], [futures.state], [futures.errors])

What does this program print?

```cpp
#include <future>
#include <iostream>

int main() {
  std::future<int> f;
  {
    std::promise<int> p;
    f = p.get_future();
  }
  try {
    std::cout << f.get() << '\n';
  } catch (const std::future_error& e) {
    std::cout << (e.code() == std::future_errc::broken_promise) << '\n';
  }
}
```

A. `0`, the value-initialized `int`
B. Nothing: `f.get()` blocks forever because no value is ever set
C. `1`
D. Undefined behavior: the future outlives its promise

**Answer (C):** `1`

**Why:** Destroying a promise whose shared state is not ready abandons the state: it stores a `future_error` with `broken_promise` and makes the state ready. So `get()` does not block; it throws, and the comparison prints `1`. The future keeps the shared state alive by itself, so outliving the promise is normal, not undefined.

### Question 2 [warmup] ([futures.async], [futures.unique.future])

What does this program print?

```cpp
#include <future>
#include <iostream>
#include <stdexcept>

int main() {
  auto f = std::async(std::launch::async, []() -> int {
    throw std::runtime_error("boom");
  });
  try {
    std::cout << f.get() << '\n';
  } catch (const std::runtime_error& e) {
    std::cout << "caught " << e.what() << '\n';
  }
}
```

A. Nothing: `std::terminate` is called because the exception escapes a thread
B. `caught boom`
C. `0`, because the task produced no value
D. Nothing: `get` throws `std::future_error` with `broken_promise`, which is not caught

**Answer (B):** `caught boom`

**Why:** `std::async` runs the function so that an exception it throws is stored in the shared state rather than escaping the thread. `get()` then rethrows that exception in the calling thread, where the handler catches it. Termination is what happens with a raw `std::thread`, which is the tempting confusion; `broken_promise` only arises when a provider is destroyed without storing anything.

### Question 3 [warmup] ([futures.promise], [futures.errors])

What does this program print?

```cpp
#include <future>
#include <iostream>

int main() {
  std::promise<int> p;
  auto f1 = p.get_future();
  try {
    auto f2 = p.get_future();
  } catch (const std::future_error& e) {
    std::cout << (e.code() == std::future_errc::future_already_retrieved) << '\n';
  }
  p.set_value(5);
  std::cout << f1.get() << '\n';
}
```

A. `5` only: the second call returns another future to the same state
B. `1` and then an exception from `f1.get()`, because the failed call broke the state
C. `0` then `5`
D. `1` then `5`

**Answer (D):** `1` then `5`

**Why:** A promise hands out exactly one future. The second `get_future` throws `future_error` with `future_already_retrieved`, and the comparison prints `1`. The failed call leaves the shared state untouched, so `set_value(5)` and `f1.get()` work normally. Sharing a result between several consumers is the job of `shared_future`, not of repeated `get_future` calls.

### Question 4 [tricky] ([futures.async], [futures.state], [class.temporary])

What is guaranteed about the output?

```cpp
#include <chrono>
#include <cstdio>
#include <future>
#include <thread>

int main() {
  std::async(std::launch::async, [] {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    std::puts("a");
  });
  std::async(std::launch::async, [] { std::puts("b"); });
}
```

A. `a` then `b`
B. `b` then `a`, because the second task does not sleep
C. `a` and `b` in an unspecified order
D. Possibly nothing, because `main` may return before either task runs

**Answer (A):** `a` then `b`

**Why:** Each call returns a temporary future that is destroyed at the end of its full-expression. Because that future is the last reference to a shared state created by `std::async` with a launched thread, the thread's completion synchronizes with the return from that release, so the destructor waits for the first task before the second call starts. The two tasks therefore run one after the other. The tempting `b` then `a` assumes the futures can be dropped without waiting, which is true only of futures from promises and packaged tasks. Compilers warn here because `std::async` is `[[nodiscard]]` since C++20, but the code is valid.

### Question 5 [tricky] ([futures.async], [futures.unique.future])

Which statement about this loop is correct?

```cpp
#include <chrono>
#include <future>

int main() {
  using namespace std::chrono_literals;
  auto f = std::async([] { return 42; });
  while (f.wait_for(10ms) != std::future_status::ready) {
    // do other work
  }
  return f.get();
}
```

A. It always ends, because the default policy is `std::launch::async`
B. It may never end: if the implementation chose deferred execution, `wait_for` returns `deferred` and never runs the function
C. It always ends, because `wait_for` runs a deferred function when it is called
D. It is undefined behavior to call `wait_for` on a future from `std::async`

**Answer (B):** It may never end: if the implementation chose deferred execution, `wait_for` returns `deferred` and never runs the function

**Why:** With no policy argument, `std::async` uses `launch::async | launch::deferred` and the implementation may pick either. A deferred function only runs on a call to `get` or a non-timed `wait`; the timed waits just return `future_status::deferred`. So if deferred is chosen, the loop condition never becomes false. Mainstream implementations usually launch a thread here, which is why the first option is tempting, but the standard does not require it.

### Question 6 [tricky] ([futures.task.members], [futures.errors])

What does this program print?

```cpp
#include <future>
#include <iostream>

int main() {
  std::packaged_task<int()> task([] { return 7; });
  auto f = task.get_future();
  task();
  try {
    task();
  } catch (const std::future_error& e) {
    std::cout << (e.code() == std::future_errc::promise_already_satisfied);
  }
  std::cout << f.get() << '\n';
}
```

A. `7`: the second call just recomputes into the same state
B. `07`
C. `17`
D. `1` and then `get()` throws, because the second call broke the state

**Answer (C):** `17`

**Why:** The first call stores 7 and makes the shared state ready. A second call would have to store into a state that is already satisfied, so it throws `future_error` with `promise_already_satisfied` and prints `1`. The stored 7 is unaffected, so `f.get()` returns it. To run a task again you must call `reset()`, which creates a new shared state and requires a new future.

### Question 7 [standardese] ([futures.unique.future])

What does the C++23 standard say about the second `f.get()`?

```cpp
#include <future>
#include <iostream>

int main() {
  std::future<int> f = std::async(std::launch::async, [] { return 1; });
  std::cout << f.get() << '\n';
  std::cout << f.get() << '\n';
}
```

A. It returns 1 again, because the value stays in the shared state
B. It is required to throw `future_error` with `no_state`
C. Undefined behavior
D. It is ill-formed, because `get` may be called only once

**Answer (C):** Undefined behavior

**Why:** `future::get` releases the shared state, so afterwards `valid()` is false. [futures.unique.future] says that calling any member other than the destructor, move assignment, `share` or `valid` on such a future is undefined. Throwing `future_error` with `no_state` is only recommended practice, which libstdc++ follows, so it is not a guarantee. Returning the value again is what `shared_future::get` does.

### Question 8 [standardese] ([futures.async], [futures.state])

Under the C++23 standard, which future's destructor may block waiting for unfinished work?

A. Any `std::future` whose shared state is not yet ready
B. The last future referring to a state from `std::async` called with `std::launch::deferred`
C. A future obtained from a `std::packaged_task` that is running on another thread
D. The last future or shared_future referring to a not-yet-ready state created by `std::async` that launched a thread

**Answer (D):** The last future or shared_future referring to a not-yet-ready state created by `std::async` that launched a thread

**Why:** [futures.async] requires the completion of a thread launched by `std::async` to synchronize with the return of the last function that releases the shared state, if no one has observed readiness first, which forces that release to wait. No such rule exists for promises or packaged tasks, whose futures release their state immediately. A deferred function never runs if nobody calls `get` or `wait`, so its future has nothing to wait for.

# C++20 coroutines and C++23 std::generator

> How C++20 stackless coroutines compile into resumable state-machine frames, how promise_type, awaitables, and symmetric transfer govern suspension, and how C++23 std::generator and lifetime rules keep async code sound.

- **Source:** C++ Atlas (https://cppatlas.com/topics/coroutines)
- **Track:** Concurrency
- **Estimated reading time:** 10 minutes
- **ISO C++ clauses:** [dcl.fct.def.coroutine] (https://eel.is/c++draft/dcl.fct.def.coroutine), [expr.await] (https://eel.is/c++draft/expr.await), [coroutine.handle] (https://eel.is/c++draft/coroutine.handle), [coroutine.traits] (https://eel.is/c++draft/coroutine.traits), [coro.generator] (https://eel.is/c++draft/coro.generator)
- **cppreference links:** [Coroutines (C++20)](https://en.cppreference.com/w/cpp/language/coroutines), [Coroutine support library](https://en.cppreference.com/w/cpp/coroutine), [std::coroutine_handle](https://en.cppreference.com/w/cpp/coroutine/coroutine_handle), [std::coroutine_traits](https://en.cppreference.com/w/cpp/coroutine/coroutine_traits), [std::suspend_always](https://en.cppreference.com/w/cpp/coroutine/suspend_always), [std::suspend_never](https://en.cppreference.com/w/cpp/coroutine/suspend_never), [std::noop_coroutine](https://en.cppreference.com/w/cpp/coroutine/noop_coroutine), [std::generator](https://en.cppreference.com/w/cpp/coroutine/generator)
- **Prerequisites:** object-lifetime-and-storage, lambdas, threads-jthread-and-locks

A C++20 coroutine is not a lightweight OS thread or a fiber with a separate stack. It is a compiler-transformed state machine whose suspension points and local variables live in a resumable **coroutine state** (frame), giving callers deterministic, zero-kernel-trap pausing and resumption.

## What makes a function a stackless coroutine

A function becomes a coroutine solely by its body containing `co_await`, `co_yield`, or `co_return`—the function signature (`Task fetch(int id)`) does not announce coroutine status. Because C++ coroutines are **stackless**, suspending a coroutine pauses only that function's own frame, storing parameters, locals that cross suspension points, the `promise` object, and a suspension-point index inside a compiler-generated coroutine state. Control returns cleanly to the immediate caller along the ordinary C++ call stack.

By default, the coroutine state is allocated dynamically via `operator new` (which `promise_type` may overload for arena or pool allocation). Under `[dcl.fct.def.coroutine]`, the compiler may perform **Heap Allocation eLision Optimization (HALO)**—placing the frame directly on the caller's stack—whenever it can prove the coroutine's lifetime nests strictly inside the caller and its size is statically known.

> **Mental model.** Calling a coroutine does not spawn background execution: it builds a state-machine frame, runs until its first suspension point, hands back the return object, and advances only when someone calls `handle.resume()`.

## The promise_type lifecycle from entry to final_suspend

When compiling a coroutine returning `R` with parameter types `Args...`, the compiler instantiates `std::coroutine_traits<R, Args...>::promise_type` (which defaults to `R::promise_type`). Entry and exit follow a fixed choreography:

1. Allocate the coroutine frame and move-or-copy parameter values into it.
2. Construct the `promise` inside the frame and invoke `promise.get_return_object()` (converting/storing the result for the caller).
3. Execute `co_await promise.initial_suspend()` (returning `std::suspend_always` for lazy tasks, or `std::suspend_never` for eager start).
4. Run the coroutine body; uncaught exceptions transfer to `promise.unhandled_exception()`, while `co_return` invokes `return_void()` or `return_value(expr)`.
5. Execute `co_await promise.final_suspend()`, which **must** be `noexcept`.

If `final_suspend()` returns `std::suspend_never`, the coroutine frame self-destructs immediately when control reaches the end—so any wrapper `Task` that later checks `handle.done()` or calls `handle.destroy()` in `~Task()` commits a use-after-free. Therefore, RAII `Task` types almost always suspend at `final_suspend()` (via `std::suspend_always` or a symmetric-transfer awaiter) so `~Task()` owns `handle.destroy()`.

```cpp
#include <coroutine>
#include <exception>
#include <utility>

struct Task {
    struct promise_type {
        std::coroutine_handle<> continuation = std::noop_coroutine();

        Task get_return_object() noexcept {
            return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
        }
        std::suspend_always initial_suspend() noexcept { return {}; }
        struct FinalAwaiter {
            bool await_ready() noexcept { return false; }
            std::coroutine_handle<> await_suspend(
                std::coroutine_handle<promise_type> h) noexcept {
                return h.promise().continuation; // Symmetric tail transfer
            }
            void await_resume() noexcept {}
        };
        FinalAwaiter final_suspend() noexcept { return {}; }
        void return_void() noexcept {}
        void unhandled_exception() { std::terminate(); }
    };

    std::coroutine_handle<promise_type> handle;
    explicit Task(std::coroutine_handle<promise_type> h) noexcept : handle(h) {}
    Task(Task&& other) noexcept : handle(std::exchange(other.handle, {})) {}
    Task& operator=(Task&&) = delete;
    ~Task() { if (handle) handle.destroy(); }
};
```

## The awaitable protocol and symmetric transfer

Every `co_await expr` evaluates a three-step customization pipeline. First, if `promise_type` defines `await_transform`, the compiler transforms `expr` via `promise.await_transform(expr)`. Second, if the resulting awaitable provides a member or non-member `operator co_await`, that operator yields the awaiter. Third, the compiler calls `awaiter.await_ready()`: if `true`, execution skips suspension and calls `await_resume()` immediately; if `false`, the coroutine saves its registers and suspension index, enters the suspended state, and calls `awaiter.await_suspend(h)`.

The return type of `await_suspend(std::coroutine_handle<Promise> h)` governs what executes next:

- **`void`** keeps `h` suspended and returns control to whichever caller resumed `h`.
- **`bool`** keeps `h` suspended when `true`, or immediately resumes `h` when `false` (useful to close lock-free race windows).
- **`std::coroutine_handle<>`** triggers **symmetric transfer**: the compiler tail-calls `.resume()` on the returned handle (or `std::noop_coroutine()` to bounce back to the resumer) without pushing a new stack frame. Calling `continuation.resume()` inside a `void`-returning `await_suspend` consumes O(N) call stack frames across loops of `co_await` calls and risks stack overflow, whereas returning `continuation` runs in constant stack space.

> **Standardese.** Under `[expr.await]`, the coroutine state is already suspended *before* `await_suspend(h)` executes. If `await_suspend` hands `h` off to another thread pool or executor, that worker may resume and destroy `h` concurrently—so never touch `this`, `h.promise()`, or frame locals after publishing `h`.

## Lifetime hazards across suspension points

Because a suspended coroutine frequently outlives the full-expression that created it, two argument-passing idioms introduce silent dangling references:

First, **reference and view parameters**: if you declare `Task parse(const std::string& text)` or `Task parse(std::string_view text)` and call `auto t = parse(std::string("payload"));`, the coroutine frame stores a reference or pointer—not a copied `std::string`. At the semicolon, the temporary string is destroyed while `t` remains suspended, leaving a dangling handle on the first `resume()`. Asynchronous coroutines should accept owning values (`std::string`) in their parameter list.

Second, **lambda coroutine captures**: in `[x = 42]() -> Task { co_await std::suspend_always{}; use(x); }()`, captured `x` lives inside the lambda closure object, *not* in the coroutine's parameters. Only the closure's `this` pointer is copied into the coroutine frame. When the temporary lambda dies at the semicolon after returning `Task`, resuming `Task` reads a destroyed closure! Either keep the closure alive across the coroutine's entire lifetime or pass values as parameters to the lambda instead of capturing them.

> **Pitfall.** Coroutine frames copy or move declared function parameters, never the pointees behind `const T&`, `std::string_view`, `std::span`, or lambda captures. Any state read after a suspension point must be owned inside the frame or guaranteed to outlive the coroutine handle.

```cpp
#include <coroutine>
#include <string>

struct DemoTask {
    struct promise_type {
        DemoTask get_return_object() noexcept { return {}; }
        std::suspend_always initial_suspend() noexcept { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        void return_void() noexcept {}
        void unhandled_exception() {}
    };
};

// Safe: owns its own std::string inside the coroutine frame
DemoTask consume_owned(std::string payload) {
    co_await std::suspend_always{};
    (void)payload.size();
}

// Safe alternative for lambdas: pass captured data as an argument, not a capture
auto make_coro = [](int x) -> DemoTask {
    co_await std::suspend_always{};
    (void)x;
};
```

## C++23 std::generator and recursive co_yield

Writing a custom `promise_type` just to produce lazy sequences is verbose and error-prone. `co_yield expr` is pure syntax sugar for `co_await promise.yield_value(expr)`, and C++23 `<generator>` packages that pattern into `std::generator<Ref, V, Allocator>`, a standard synchronous `std::ranges::view` compatible with range pipelines.

Even better, C++23 `std::generator` solves the classic recursive-generator slowdown via `std::ranges::elements_of`. Yielding elements of a nested generator with a manual `for (auto x : child()) co_yield x;` loop incurs O(depth) trampoline hops on every yielded item. Calling `co_yield std::ranges::elements_of(child())` pushes the child coroutine onto an internal active-coroutine stack inside the root generator and transfers directly to the innermost leaf in O(1) per element.

```cpp
#include <generator>
#include <ranges>

std::generator<int> range_seq(int lo, int hi) {
    for (int i = lo; i < hi; ++i) {
        co_yield i;
    }
}

std::generator<int> chained_seq() {
    co_yield std::ranges::elements_of(range_seq(0, 3));
    co_yield std::ranges::elements_of(range_seq(10, 13));
}
```

Each promise customization hook maps cleanly to a distinct phase of the coroutine lifecycle:

| Customization Point | When Invoked | Key Invariant |
| --- | --- | --- |
| `initial_suspend()` | Right after `get_return_object()` | `suspend_always` builds lazy tasks; `suspend_never` runs eagerly |
| `final_suspend()` | After `return_*` or `unhandled_exception()` | Must be `noexcept`; suspending transfers `destroy()` ownership to caller |
| `await_transform(e)` | Before `operator co_await` on every `co_await e` | Lets promises intercept or wrap arbitrary awaited expressions |
| `yield_value(v)` | On every `co_yield v` | Lowers directly to `co_await promise.yield_value(v)` |
| `await_suspend(h)` | After `h` is suspended and `await_ready()` is false | Returning `coroutine_handle<>` triggers constant-stack symmetric transfer |

## What to remember

- A function is a coroutine solely because its body uses `co_await`, `co_yield`, or `co_return`; stackless frames store spilled locals without needing OS thread stacks.
- Make `final_suspend()` `noexcept` and suspend if an owning wrapper like `Task` later calls `handle.done()` or `handle.destroy()`.
- Prefer `std::coroutine_handle<>`-returning `await_suspend` for symmetric transfer so chained async continuations never overflow the call stack.
- Never touch `this`, `h.promise()`, or frame locals after handing `h` to another thread inside `await_suspend`, because the coroutine is already suspended and may finish concurrently.
- Pass asynchronous coroutine inputs by owning value—not `const T&`, `string_view`, or temporary lambda captures—and use C++23 `std::generator` with `std::ranges::elements_of` for synchronous lazy streams.

## Concept Map Outline

- **C++20 coroutines & generator:** Compiler-generated stackless state machines pause and resume without separate OS thread stacks.
  - **Stackless frame mechanics:** Compiler transforms functions containing co_await, co_yield, or co_return into frames.
    - **Frame stores spilled locals:** Holds promise, copied parameters, suspension index, and cross-suspend variables.
    - **Custom operator new & HALO:** Promises may override allocation; compilers elide heap frames when lifetimes nest.
    - **Runs on resumer thread:** Calling or resuming a coroutine executes synchronously on the invoking thread.
  - **Promise lifecycle:** coroutine_traits<R, Args...>::promise_type orchestrates startup, returns, and teardown.
    - **initial_suspend laziness:** Returns suspend_always for lazy start or suspend_never for eager execution.
    - **final_suspend must be noexcept:** Suspending lets RAII wrappers call destroy(); suspend_never self-deletes the frame.
    - **unhandled_exception hook:** Captures uncaught body exceptions inside the promise before final_suspend runs.
  - **Awaitable protocol:** co_await drives await_transform, await_ready, await_suspend, and await_resume.
    - **await_ready bypass:** Returns true when results are already ready, avoiding suspension overhead.
    - **Symmetric transfer handle:** Returning coroutine_handle<> from await_suspend tail-resumes without stack growth.
    - **Suspended before await_suspend:** Another thread can resume and destroy h immediately once await_suspend publishes h.
  - **Suspension lifetime hazards:** References and closure captures outlive temporaries across suspension boundaries.
    - **Reference & view parameters:** const T& and string_view bind temporaries that die at the caller semicolon.
    - **Lambda capture closure trap:** Temporary coroutine lambdas destroy captures at the semicolon, leaving dangling this.
    - **Pass owning values:** By-value parameters move directly into the coroutine frame for safe later access.
  - **C++23 std::generator:** Standard synchronous ranges::view backed by co_yield and promise.yield_value.
    - **co_yield lowers to co_await:** Every co_yield x evaluates co_await promise.yield_value(x).
    - **elements_of O(1) recursion:** Yielding nested generators via elements_of avoids linear trampoline overhead.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.fct.def.coroutine])

A Task RAII wrapper holds std::coroutine_handle<promise_type> h and calls if (h) h.destroy(); in ~Task(). What happens if promise_type::final_suspend() returns std::suspend_never?

A. h.destroy() safely releases any remaining promise fields
B. When the coroutine finishes, its frame self-destructs before ~Task() runs, causing double destruction / use-after-free in ~Task()
C. Compilation fails unless final_suspend() returns std::suspend_always
D. The coroutine restarts from initial_suspend()

**Answer (B):** When the coroutine finishes, its frame self-destructs before ~Task() runs, causing double destruction / use-after-free in ~Task()

**Why:** Under [dcl.fct.def.coroutine], if a coroutine does not suspend at final_suspend(), execution flows off the end and automatically destroys the coroutine state. Any Task handle still pointing to that frame now dangles, so checking h.done() or calling h.destroy() in ~Task() is undefined behavior.

### Question 2 [warmup] ([expr.yield])

Inside a coroutine body, how does the compiler translate co_yield expr;?

A. Into co_await promise.yield_value(expr);
B. Into promise.return_value(expr);
C. Into co_await expr; bypassing the promise
D. Into a thread yield call std::this_thread::yield()

**Answer (A):** Into co_await promise.yield_value(expr);

**Why:** Per [expr.yield], co_yield expr is defined to be equivalent to co_await p.yield_value(expr), where p is the coroutine's promise object.

### Question 3 [tricky] ([dcl.fct.def.coroutine], [expr.prim.lambda.closure])

Assuming Task starts lazily (initial_suspend() returns std::suspend_always), what happens when t.handle.resume() executes below?

```cpp
Task t = [msg = std::string("hello")]() -> Task {
    co_await std::suspend_always{};
    std::size_t n = msg.size();
    (void)n;
}();
t.handle.resume();
```

A. msg was copied into the coroutine frame automatically, so msg.size() returns 5
B. Compilation fails because lambdas cannot be coroutines
C. Undefined behavior: the temporary lambda closure dies at the semicolon while t is suspended, so msg inside the coroutine reads a dangling closure this
D. HALO automatically extends the lambda closure lifetime to match t

**Answer (C):** Undefined behavior: the temporary lambda closure dies at the semicolon while t is suspended, so msg inside the coroutine reads a dangling closure this

**Why:** A coroutine lambda's captures reside in the closure object (*this), not in the coroutine's parameter list. Calling (...)() stores only the closure's this pointer inside the coroutine frame; when the temporary closure is destroyed at the semicolon, resuming t later dereferences a dangling this pointer.

### Question 4 [tricky] ([dcl.fct.def.coroutine], [class.temporary])

Why does make_task(std::string("transient")) exhibit undefined behavior when resumed after its initial suspension point?

```cpp
Task make_task(std::string_view sv) {
    co_await std::suspend_always{};
    use(sv);
}
Task t = make_task(std::string("transient"));
t.handle.resume();
```

A. std::string_view cannot be copied into a coroutine frame
B. co_await std::suspend_always{} clears all parameters
C. std::string temporaries cannot convert to std::string_view in coroutines
D. The coroutine frame stores a copy of sv (a pointer+length view), while the temporary std::string is destroyed at the semicolon before t.handle.resume() runs

**Answer (D):** The coroutine frame stores a copy of sv (a pointer+length view), while the temporary std::string is destroyed at the semicolon before t.handle.resume() runs

**Why:** Coroutine parameters are copied/moved into the frame according to their declared parameter types. Because sv is a non-owning std::string_view (just like const std::string&), it does not extend or copy the backing std::string temporary, which dies at the end of the full-expression creating t.

### Question 5 [standardese] ([expr.await])

In void await_suspend(std::coroutine_handle<> h), the awaiter pushes h into a lock-free queue watched by another thread, and then reads this->result on the next line of await_suspend. Why is this a race / use-after-free?

A. await_suspend cannot accept a type-erased std::coroutine_handle<>
B. The coroutine is already suspended before await_suspend begins ([expr.await]), so the worker thread can resume and destroy the coroutine (and the awaited temporary awaiter) before await_suspend finishes
C. await_suspend automatically holds an internal mutex on h
D. Only bool await_suspend permits multi-threaded resumption

**Answer (B):** The coroutine is already suspended before await_suspend begins ([expr.await]), so the worker thread can resume and destroy the coroutine (and the awaited temporary awaiter) before await_suspend finishes

**Why:** Under [expr.await], the coroutine saves state and suspends before await_suspend(h) is entered. Once h is published to another thread, that thread may immediately resume h, run past co_await, and destroy both h and any stack/member awaiter object before await_suspend returns.

### Question 6 [standardese] ([expr.await], [coroutine.handle.noop])

How does returning std::coroutine_handle<> from await_suspend prevent stack overflow across long chains of completed coroutines, and what handle stops the chain?

A. It pushes continuations onto a heap queue; nullptr stops the chain
B. It spawns a fresh thread for each continuation; std::coroutine_handle<>::from_address(nullptr) stops it
C. It performs symmetric transfer via a tail call to the returned handle's resume() without growing the stack; returning std::noop_coroutine() returns control to the caller
D. It runs await_resume() recursively and unwinds with exceptions

**Answer (C):** It performs symmetric transfer via a tail call to the returned handle's resume() without growing the stack; returning std::noop_coroutine() returns control to the caller

**Why:** Under [expr.await], if await_suspend returns a std::coroutine_handle<Z>, the compiler emits a tail transfer calling resume() on that handle without allocating another C++ stack frame. Returning std::noop_coroutine() invokes a no-op resumption that immediately returns control to whichever caller invoked resume().

# Coroutine library and generators

> The <coroutine> header gives you a raw, non-owning handle to a coroutine frame and two trivial awaiters, and everything else is yours to build. This page builds a minimal generator and a minimal task on top of those pieces, then shows what C++23's std::generator does for you and where its lifetimes still bite.

- **Source:** C++ Atlas (https://cppatlas.com/topics/coroutine-library-and-generators)
- **Track:** Concurrency
- **Estimated reading time:** 15 minutes
- **ISO C++ clauses:** [coroutine.handle] (https://eel.is/c++draft/coroutine.handle), [coroutine.handle.resumption] (https://eel.is/c++draft/coroutine.handle.resumption), [coroutine.handle.observers] (https://eel.is/c++draft/coroutine.handle.observers), [coroutine.noop] (https://eel.is/c++draft/coroutine.noop), [coroutine.trivial.awaitables] (https://eel.is/c++draft/coroutine.trivial.awaitables), [coro.generator] (https://eel.is/c++draft/coro.generator), [coro.generator.promise] (https://eel.is/c++draft/coro.generator.promise), [range.elementsof] (https://eel.is/c++draft/range.elementsof), [stmt.ranged] (https://eel.is/c++draft/stmt.ranged)
- **cppreference links:** [std::coroutine_handle](https://en.cppreference.com/w/cpp/coroutine/coroutine_handle), [std::coroutine_handle::resume](https://en.cppreference.com/w/cpp/coroutine/coroutine_handle/resume), [std::coroutine_handle::done](https://en.cppreference.com/w/cpp/coroutine/coroutine_handle/done), [std::noop_coroutine](https://en.cppreference.com/w/cpp/coroutine/noop_coroutine), [std::suspend_always](https://en.cppreference.com/w/cpp/coroutine/suspend_always), [std::generator](https://en.cppreference.com/w/cpp/coroutine/generator), [std::generator::begin](https://en.cppreference.com/w/cpp/coroutine/generator/begin), [std::ranges::elements_of](https://en.cppreference.com/w/cpp/ranges/elements_of)
- **Prerequisites:** coroutines, ranges-and-views, raii-and-resource-management

## The one idea

The language part of coroutines, covered in the coroutines topic, decides *when* a function suspends and which promise methods run. The library part is small: a handle type that points at a coroutine frame, a way to get from the promise to the handle and back, a coroutine that does nothing, and two awaiters that always or never suspend. Generators, tasks and schedulers are ordinary classes that wrap a handle and manage its lifetime by hand.

> **Mental model.** A `std::coroutine_handle` is to a coroutine frame what a raw pointer is to a heap object. It is copyable, does not own anything, and every operation on it has a precondition about the state of the thing it points to. A return object such as a generator is the `unique_ptr` around it: it destroys the frame exactly once and is therefore move-only.

## coroutine_handle and its preconditions

`std::coroutine_handle<Promise>` knows the promise type and can reach the promise; `std::coroutine_handle<void>`, also spelled `std::coroutine_handle<>`, is the type-erased form that any typed handle converts to implicitly. Only the typed form has `promise()` and the static `from_promise(p)`, which recovers the handle from a reference to the promise. That is how `get_return_object` usually builds the return object. Both forms have `address()` and `from_address()` for passing the frame through C APIs as a `void*`, plus comparison and hashing. A default-constructed handle is null.

| Call | Precondition | If violated |
|---|---|---|
| `resume()` or `h()` | refers to a suspended coroutine not at its final suspend point | undefined behavior |
| `destroy()` | refers to a suspended coroutine, at any suspension point | undefined behavior |
| `done()` | refers to a suspended coroutine | undefined behavior |
| `promise()` | refers to a coroutine that has not been destroyed | undefined behavior |
| `from_promise(p)` | `p` is a reference to the promise object of a coroutine | undefined behavior |

`done()` returns true exactly when the coroutine is suspended at its final suspend point. It cannot tell you that a frame has been destroyed, because a destroyed frame no longer satisfies the precondition. If `final_suspend` does not suspend, the frame destroys itself when the body ends, and every copy of the handle becomes dangling at that moment. A handle-based design therefore almost always suspends at the final point and lets the owner call `destroy()`.

Resuming a coroutine from another thread is allowed; the handle is just an address. But two threads must never resume the same coroutine concurrently, and a resumer must not race with the owner's `destroy()`. Those are your synchronization problems, not the library's.

## noop_coroutine and the trivial awaitables

`std::noop_coroutine()` returns a `std::noop_coroutine_handle`, a handle to a coroutine that does nothing. Its `resume()` and `destroy()` have no effect, `done()` always returns false, and it converts to `std::coroutine_handle<>`. Its main use is as the "nothing to resume" value in symmetric transfer: an `await_suspend` that returns `std::noop_coroutine()` hands control back to whoever resumed the current coroutine.

```cpp
#include <coroutine>
#include <cstdio>

int main() {
  auto n = std::noop_coroutine();
  n.resume();                          // no effect
  n.destroy();                         // no effect
  std::printf("%d\n", n.done());       // prints 0, always
  std::coroutine_handle<> h = n;       // converts like any typed handle
  (void)h;
}
```

`std::suspend_always` and `std::suspend_never` are empty structs whose `await_ready` returns false and true respectively, with empty `await_suspend` and `await_resume`. All their members are `constexpr` and `noexcept`, which matters because `final_suspend` must not be potentially-throwing.

> **Standardese.** [coroutine.noop] says handles returned by different calls to `noop_coroutine` may or may not compare equal. Do not use `h == std::noop_coroutine()` as a test for "is this the no-op handle"; keep a flag or compare against a stored copy.

## A minimal generator, step by step

A generator needs four decisions. It suspends initially, so nothing runs until the consumer asks. Its `yield_value` stores the value in the promise and suspends. It suspends finally, so `done()` remains callable. Its owner destroys the frame. Exceptions are captured in `unhandled_exception` and rethrown to the consumer.

```cpp
#include <coroutine>
#include <cstdio>
#include <exception>
#include <utility>

template <class T>
class Gen {
public:
  struct promise_type {
    T value;
    std::exception_ptr error;
    Gen get_return_object() {
      return Gen{std::coroutine_handle<promise_type>::from_promise(*this)};
    }
    std::suspend_always initial_suspend() noexcept { return {}; }   // lazy start
    std::suspend_always final_suspend() noexcept { return {}; }     // keep frame for done()
    std::suspend_always yield_value(T v) { value = std::move(v); return {}; }
    void return_void() {}
    void unhandled_exception() { error = std::current_exception(); }
  };

  explicit Gen(std::coroutine_handle<promise_type> h) : h_(h) {}
  Gen(Gen&& o) noexcept : h_(std::exchange(o.h_, {})) {}
  Gen& operator=(Gen) = delete;
  ~Gen() { if (h_) h_.destroy(); }    // destroy works at any suspension point

  bool next() {                       // advance; false when finished
    h_.resume();
    if (h_.promise().error) std::rethrow_exception(h_.promise().error);
    return !h_.done();
  }
  const T& value() const { return h_.promise().value; }

private:
  std::coroutine_handle<promise_type> h_;
};

Gen<int> count_to(int n) {
  for (int i = 1; i <= n; ++i) co_yield i;
}

int main() {
  auto g = count_to(3);
  while (g.next()) std::printf("%d\n", g.value());   // 1 2 3
}
```

Calling `next()` again after it has returned false would resume a coroutine at its final suspend point, which is undefined behavior; a production generator guards against it. Stopping the loop early is fine, because the destructor destroys the suspended frame and runs the destructors of whatever locals were live at the `co_yield`. This design requires `T` to be default-constructible and copies every value into the promise; `std::generator` avoids both by storing a pointer to the yielded object instead.

## A minimal task with symmetric transfer

A task is a lazy coroutine that produces one value and resumes whoever awaited it. The awaiting side stores its own handle as the continuation and returns the child's handle, so starting the child is a transfer rather than a nested call. At the end, the child's final awaiter returns the continuation, which is `std::noop_coroutine()` if nobody is waiting.

```cpp
#include <coroutine>
#include <cstdio>
#include <exception>
#include <optional>
#include <utility>

template <class T>
class Task {
public:
  struct promise_type {
    std::optional<T> result;
    std::exception_ptr error;
    std::coroutine_handle<> continuation = std::noop_coroutine();

    Task get_return_object() {
      return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
    }
    std::suspend_always initial_suspend() noexcept { return {}; }

    struct FinalAwaiter {
      bool await_ready() noexcept { return false; }
      std::coroutine_handle<> await_suspend(std::coroutine_handle<promise_type> h) noexcept {
        return h.promise().continuation;      // resume the awaiter as a tail call
      }
      void await_resume() noexcept {}
    };
    FinalAwaiter final_suspend() noexcept { return {}; }

    void return_value(T v) { result.emplace(std::move(v)); }
    void unhandled_exception() { error = std::current_exception(); }
  };

  bool await_ready() const noexcept { return false; }
  std::coroutine_handle<> await_suspend(std::coroutine_handle<> awaiting) noexcept {
    h_.promise().continuation = awaiting;
    return h_;                                 // start the child
  }
  T await_resume() {
    if (h_.promise().error) std::rethrow_exception(h_.promise().error);
    return std::move(*h_.promise().result);
  }

  T run() {                // for a non-coroutine caller, when the chain completes synchronously
    h_.resume();
    return await_resume();
  }

  explicit Task(std::coroutine_handle<promise_type> h) : h_(h) {}
  Task(Task&& o) noexcept : h_(std::exchange(o.h_, {})) {}
  ~Task() { if (h_) h_.destroy(); }

private:
  std::coroutine_handle<promise_type> h_;
};

Task<int> leaf(int x) { co_return x * 2; }
Task<int> parent() {
  int a = co_await leaf(10);
  int b = co_await leaf(a);
  co_return a + b;
}

int main() { std::printf("%d\n", parent().run()); }   // 60
```

The awaited `leaf(10)` is a temporary that lives until the end of the full-expression containing the `co_await`, which spans the whole suspension, so the child frame is still alive when `await_resume` reads its result. A real task library adds an executor, cancellation and a blocking `sync_wait`; `run()` here only works because nothing ever suspends waiting for an outside event.

## std::generator in C++23

`std::generator<Ref, V = void, Allocator = void>` in `<generator>` is a finished generator that is also a range. With the defaults, `generator<T>` has value type `remove_cvref_t<T>` and reference type `T&&`, so `generator<int>` yields `int&&`. A loop written `for (int& x : gen())` is therefore ill-formed; use a value or `auto&&`. To yield references without copies, name the reference type: `generator<const std::string&>` yields `const std::string&` and has value type `std::string`.

Yielding a prvalue binds it to the reference and suspends with the temporary still alive, so nothing is copied. Yielding an lvalue to a generator whose reference type is an rvalue reference copies it into the awaiter, which is the one case where `std::generator` makes a copy.

`co_yield std::ranges::elements_of(r)` yields every element of `r`. When `r` is another `std::generator` with the same yielded type, the inner generator is resumed directly through symmetric transfer, so recursive generators do not stack an iteration loop per level. For any other range, the elements' reference type must convert to the generator's yielded type, which surprises people with `generator<int>`.

```cpp
#include <generator>
#include <ranges>
#include <vector>

struct Node { int v; Node* l; Node* r; };

std::generator<int> inorder(const Node* n) {
  if (!n) co_return;
  co_yield std::ranges::elements_of(inorder(n->l));   // nested generator: direct transfer
  co_yield n->v;
  co_yield std::ranges::elements_of(inorder(n->r));
}

std::generator<int> evens() {
  std::vector<int> v{0, 2, 4};
  // co_yield std::ranges::elements_of(v);            // ill-formed: int& does not convert to int&&
  co_yield std::ranges::elements_of(v | std::views::as_rvalue);   // OK
}
```

A `std::generator` is a move-only `view` that models `input_range` only: it is not copyable, not a forward range, not sized and not common. `begin()` resumes the coroutine for the first time, and its precondition is that the coroutine is still at its initial suspend point, so calling `begin()` twice, including by iterating the same generator in two loops, is undefined behavior.

For allocation, a generator coroutine may take `std::allocator_arg_t` and an allocator as its first two parameters, and the promise's `operator new` uses that allocator for the frame. With `Allocator = void`, any allocator can be passed this way and is stored type-erased in the frame; with a concrete `Allocator`, only allocators convertible to it are accepted.

> **Pitfall.** GCC 16's libstdc++ ships `std::generator`, but Clang 21's libc++ does not yet have the header, so portable code may still need a fallback such as the hand-written generator above.

## Lifetime pitfalls with range-for

A generator taking a reference parameter keeps only the reference. When the generator object is stored in a variable, any temporary argument dies at the end of that declaration, before the body runs:

```cpp
#include <generator>
#include <string>

std::generator<char> chars(const std::string& s) { for (char c : s) co_yield c; }

void demo() {
  auto g = chars(std::string("hello"));     // the string dies here
  for (char c : g) (void)c;                 // undefined behavior

  for (char c : chars(std::string("hello"))) (void)c;   // OK since C++23
}
```

The second loop is safe only because of P2718, adopted for C++23: temporaries created in a range-for initializer now live until the end of the loop. Before C++23 that loop dangled too. The rule covers only the initializer of the loop itself, not a generator object created earlier, and GCC 16 applies it in `-std=c++23` mode, where `-fno-range-for-ext-temps` turns it off and AddressSanitizer then reports the use after scope. The safe habit has not changed: take generator parameters by value, or make sure the referent outlives the generator object.

> **Pitfall.** Range adaptors do not change any of this. Piping `chars(std::string("x")) | std::views::take(2)` into a loop is covered by the C++23 extension, but storing the pipeline in a variable first is not.

## What to remember

- `coroutine_handle` is a non-owning pointer to a frame; `resume`, `destroy`, `done` and `promise` all require a suspended, still-existing coroutine.
- `done()` is true only at the final suspend point, so suspend there if anyone will ask; resuming from there is undefined behavior.
- `noop_coroutine()` handles do nothing when resumed or destroyed, report `done() == false`, and need not compare equal to each other.
- `suspend_always` and `suspend_never` are constexpr, noexcept trivial awaiters.
- A generator suspends initially and finally, stores or points to the yielded value, and owns the handle as a move-only RAII type.
- A task stores its awaiter as a continuation and uses handle-returning `await_suspend` for both start and finish.
- `std::generator<T>` yields `T&&`; use `generator<const T&>` to yield references, and `elements_of` for nested generators.
- `elements_of` on a non-generator range needs its reference type to convert to the yielded type.
- `std::generator` is a move-only input view; calling `begin()` twice is undefined behavior.
- C++23 extends temporaries in a range-for initializer, but not for a generator stored in a variable first.

## Concept Map Outline

- **Coroutine library:** A non-owning handle, a no-op coroutine and two trivial awaiters; generators and tasks are built on top.
  - **coroutine_handle:** A copyable, non-owning pointer to a coroutine frame.
    - **Typed and void:** Only coroutine_handle<P> has promise() and from_promise; any typed handle converts to the void form.
    - **resume precondition:** Suspended and not at the final suspend point; otherwise undefined behavior.
    - **destroy precondition:** Suspended at any point; destroying twice or while running is undefined behavior.
    - **done:** True only at the final suspend point; calling it on a destroyed frame is UB.
  - **Trivial pieces:** Library-provided building blocks with no behavior of their own.
    - **noop_coroutine:** resume and destroy do nothing and done() is always false.
    - **noop equality:** Handles from different noop_coroutine calls may or may not compare equal.
    - **suspend_always, suspend_never:** constexpr noexcept awaiters whose await_ready returns false or true.
  - **Hand-written generator:** Suspend initially and finally, store the value in the promise, own the handle.
    - **Lazy start:** initial_suspend returns suspend_always so nothing runs before the first next().
    - **Final suspend:** Suspending at the end keeps done() valid and lets the owner destroy the frame.
    - **Move-only owner:** The destructor calls destroy once; copying would destroy twice.
  - **Hand-written task:** A lazy single-result coroutine that resumes its awaiter when it finishes.
    - **Continuation:** await_suspend stores the awaiting handle in the child's promise.
    - **Start by transfer:** await_suspend returns the child's handle instead of calling resume.
    - **Finish by transfer:** The final awaiter returns the continuation, or noop_coroutine if none.
  - **std::generator (C++23):** generator<Ref, V, Allocator> in <generator>: a coroutine that is also a range.
    - **Reference type:** generator<T> yields T&&; generator<const T&> yields references without copies.
    - **elements_of:** Nested generators transfer directly; other ranges need references convertible to the yielded type.
    - **Move-only input view:** Not copyable, forward, sized or common; begin() may be called only once.
    - **Allocator:** Pass allocator_arg and an allocator as the first two parameters to allocate the frame.
    - **Range-for temporaries:** C++23 extends temporaries in the loop initializer, not in an earlier declaration.

## Standardese Quiz Questions

### Question 1 [warmup] ([coro.generator.class])

In C++23, what type is `R`?

```cpp
#include <generator>
#include <ranges>

using R = std::ranges::range_reference_t<std::generator<int>>;
```

A. `int`
B. `int&`
C. `const int&`
D. `int&&`

**Answer (D):** `int&&`

**Why:** With the default second template argument, `std::generator<T>` uses `T&&` as its reference type, so dereferencing the iterator of a `generator<int>` gives an `int&&`. Its value type is `int`. That is why `for (int& x : g)` does not compile while `for (int x : g)` and `for (auto&& x : g)` do. Write `std::generator<const int&>` if you want lvalue references.

### Question 2 [warmup] ([coroutine.noop], [coroutine.handle.observers])

What does this program print?

```cpp
#include <coroutine>
#include <cstdio>

int main() {
  std::coroutine_handle<> h = std::noop_coroutine();
  h.resume();
  h.destroy();
  std::printf("%d\n", h.done());
}
```

A. `0`
B. `1`, because a coroutine that does nothing is immediately finished
C. Nothing: calling `destroy()` and then `done()` is undefined behavior
D. It is implementation-defined

**Answer (A):** `0`

**Why:** The no-op coroutine is never at its final suspend point: `done()` always returns false, and `resume()` and `destroy()` have no effect, even through a converted `coroutine_handle<>`. That is what makes it usable as the "resume nothing" result of a handle-returning `await_suspend`. Destroying an ordinary coroutine and then calling `done()` would be undefined behavior, but that rule does not apply here.

### Question 3 [warmup] ([coroutine.handle])

Is this function well-formed?

```cpp
#include <coroutine>

void inspect(std::coroutine_handle<> h) {
  auto& p = h.promise();
  (void)p;
}
```

A. Yes: it returns a reference to the promise as `void*`
B. Yes, but calling it with a null handle is undefined behavior
C. No: `coroutine_handle<void>` has no `promise()` member
D. No: `promise()` is a static member function

**Answer (C):** No: `coroutine_handle<void>` has no `promise()` member

**Why:** The call is ill-formed. The type-erased `std::coroutine_handle<>` does not know the promise type, so it provides only `resume`, `destroy`, `done`, `address` and the comparison operations. `promise()` and `from_promise()` exist only in `coroutine_handle<Promise>`. To reach the promise from a `void*` you would use `coroutine_handle<P>::from_address`, which is undefined behavior if `P` is not the coroutine's real promise type.

### Question 4 [tricky] ([coro.generator.promise], [range.elementsof])

In C++23, is this function well-formed?

```cpp
#include <generator>
#include <ranges>
#include <vector>

std::generator<int> evens() {
  std::vector<int> v{0, 2, 4};
  co_yield std::ranges::elements_of(v);
}
```

A. Yes: `elements_of` yields each element of any input range
B. No: `v` is an lvalue, so `int&` must convert to the yielded type `int&&`, and it does not
C. No: `elements_of` only accepts another `std::generator`
D. Yes, but each element is moved out of `v`

**Answer (B):** No: `v` is an lvalue, so `int&` must convert to the yielded type `int&&`, and it does not

**Why:** The yielded type of `std::generator<int>` is `int&&`. The `yield_value` overload for a general range requires the range's reference type to be convertible to the yielded type, and `int&` is not convertible to `int&&`, so overload resolution fails, the program is ill-formed, and GCC 16 rejects it. `elements_of` does accept arbitrary ranges; the fix is `elements_of(v | std::views::as_rvalue)`, or yielding `const int&` from a `std::generator<const int&>`.

### Question 5 [tricky] ([stmt.ranged], [class.temporary], [dcl.fct.def.coroutine])

Compiled as C++23, which of the two loops has undefined behavior?

```cpp
#include <cstdio>
#include <generator>
#include <string>

std::generator<char> chars(const std::string& s) {
  for (char c : s) co_yield c;
}

int main() {
  auto g = chars(std::string(20, 'x'));
  for (char c : g) std::putchar(c);                       // loop 1

  for (char c : chars(std::string(20, 'y'))) std::putchar(c);  // loop 2
}
```

A. Both
B. Neither: the coroutine frame keeps the string alive
C. Only loop 1
D. Only loop 2

**Answer (C):** Only loop 1

**Why:** In loop 1 the temporary string is destroyed at the end of the declaration of `g`, while the generator still holds a reference to it, so resuming the body reads a dead object. In loop 2, P2718 (C++23) extends every temporary in the range-for initializer to the end of the loop, so the string outlives the iteration. Before C++23 both loops were undefined. The frame stores the reference parameter as a reference, so it keeps nothing alive.

### Question 6 [tricky] ([coro.generator.members], [coro.generator])

What is the behavior of this program?

```cpp
#include <cstdio>
#include <generator>

std::generator<int> three() {
  co_yield 1;
  co_yield 2;
  co_yield 3;
}

int main() {
  auto g = three();
  for (int x : g) std::printf("%d ", x);
  for (int x : g) std::printf("%d ", x);
}
```

A. It prints `1 2 3 1 2 3`
B. It prints `1 2 3` and the second loop does nothing
C. It throws when the second loop starts
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** Each range-for calls `g.begin()`, and `std::generator::begin` has the precondition that the coroutine is still suspended at its initial suspend point. The first loop runs it to its final suspend point, so the second call to `begin()` violates the precondition. A generator is an input range: it cannot be restarted, and nothing in the standard makes a second pass an empty range.

### Question 7 [standardese] ([coroutine.noop], [coroutine.handle.compare])

What does the standard say about the value of `same`?

```cpp
#include <coroutine>

bool same() {
  std::coroutine_handle<> a = std::noop_coroutine();
  std::coroutine_handle<> b = std::noop_coroutine();
  return a == b;
}
```

A. It is always `true`: there is one no-op coroutine
B. It is always `false`
C. It is unspecified: different calls may or may not return handles that compare equal
D. Undefined behavior: comparing no-op handles is not allowed

**Answer (C):** It is unspecified: different calls may or may not return handles that compare equal

**Why:** [coroutine.noop] explicitly says that handles returned from different calls to `noop_coroutine` may or may not compare equal. Comparison itself is well-defined; only the result is left open, so code must not use equality with a fresh `noop_coroutine()` to detect the no-op handle. An implementation can return the same static frame every time, but it is not required to.

### Question 8 [standardese] ([coroutine.handle.resumption])

What is the behavior of the second `resume()`?

```cpp
#include <coroutine>

struct R {
  struct promise_type {
    R get_return_object() {
      return {std::coroutine_handle<promise_type>::from_promise(*this)};
    }
    std::suspend_always initial_suspend() noexcept { return {}; }
    std::suspend_always final_suspend() noexcept { return {}; }
    void return_void() {}
    void unhandled_exception() {}
  };
  std::coroutine_handle<promise_type> h;
};

R body() { co_return; }

int main() {
  R r = body();
  r.h.resume();      // runs to the final suspend point
  r.h.resume();
  r.h.destroy();
}
```

A. It has no effect, because `done()` is true
B. Undefined behavior
C. It restarts the coroutine from the beginning
D. It calls `std::terminate`

**Answer (B):** Undefined behavior

**Why:** [coroutine.handle.resumption] requires that `*this` refer to a suspended coroutine that is not suspended at its final suspend point. After the first `resume()` the coroutine sits at its final suspend point, so the second call violates the precondition. A generator or task must check `done()` before resuming; the only valid operations left are `done()`, `promise()` and `destroy()`.

# Lock-free programming and ABA

> Lock-free code replaces mutual exclusion with compare-and-swap retry loops, which buys a progress guarantee and costs you memory reclamation. This page builds the Treiber stack, shows how the ABA problem and use-after-free break it, and surveys tagged pointers, hazard pointers, RCU and atomic shared_ptr as fixes.

- **Source:** C++ Atlas (https://cppatlas.com/topics/lock-free-programming-and-aba)
- **Track:** Concurrency
- **Estimated reading time:** 15 minutes
- **ISO C++ clauses:** [intro.progress] (https://eel.is/c++draft/intro.progress), [intro.races] (https://eel.is/c++draft/intro.races), [atomics.lockfree] (https://eel.is/c++draft/atomics.lockfree), [atomics.order] (https://eel.is/c++draft/atomics.order), [atomics.types.operations] (https://eel.is/c++draft/atomics.types.operations), [atomics.flag] (https://eel.is/c++draft/atomics.flag), [util.smartptr.atomic] (https://eel.is/c++draft/util.smartptr.atomic)
- **cppreference links:** [std::atomic<T>::compare_exchange_weak, compare_exchange_strong](https://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange), [std::atomic<T>::is_always_lock_free](https://en.cppreference.com/w/cpp/atomic/atomic/is_always_lock_free), [std::atomic<T>::is_lock_free](https://en.cppreference.com/w/cpp/atomic/atomic/is_lock_free), [std::atomic_flag](https://en.cppreference.com/w/cpp/atomic/atomic_flag), [std::atomic<std::shared_ptr>](https://en.cppreference.com/w/cpp/memory/shared_ptr/atomic2), [std::memory_order](https://en.cppreference.com/w/cpp/atomic/memory_order), [std::hardware_destructive_interference_size](https://en.cppreference.com/w/cpp/thread/hardware_destructive_interference_size)
- **Prerequisites:** atomics-and-memory-ordering, mutexes-and-locks, smart-pointers

## The one idea

A lock-free data structure never makes one thread wait for another to leave a critical section. Instead, every thread reads the shared state, computes the new state privately, and tries to install it with a single compare-and-swap. If another thread got there first, the swap fails and the thread starts over. That one change gives a real progress guarantee, because a preempted thread can no longer stall everyone else. It also creates the hardest problem in the field: a thread that read a pointer can be stopped for an arbitrary time, and by the time it uses the pointer, the node may have been freed, reused, and put back.

> **Mental model.** A CAS loop is optimistic concurrency on one word. It proves only that the word holds the same bits it held when you read it, not that nothing happened in between. Everything else in lock-free programming, including ABA defences and memory reclamation schemes, exists to close that gap.

This page builds on atomics-and-memory-ordering, which covers `compare_exchange_weak` versus `compare_exchange_strong` and what each memory order means.

## Progress guarantees

Four levels of progress are usually distinguished:

- **Blocking**: a thread can be prevented from making progress indefinitely by another thread that is not running, for example one holding a mutex while preempted.
- **Obstruction-free**: a thread that runs in isolation, with all others paused, finishes in a bounded number of steps. Contention can cause livelock.
- **Lock-free**: whenever threads are running the operation, at least one of them finishes in a bounded number of steps. Individual threads can starve, but the system as a whole progresses.
- **Wait-free**: every thread finishes in a bounded number of its own steps, regardless of the others.

A Treiber stack's push is lock-free but not wait-free: a CAS only fails because some other thread's CAS succeeded, so someone always progresses, but an unlucky thread can lose every race. A `fetch_add` on hardware with an atomic add instruction, such as Arm's LSE `ldadd` or x86's `lock xadd`, is wait-free.

> **Standardese.** [intro.progress] calls executions of lock-free atomic functions lock-free executions, but it only *requires* the obstruction-free property: if only one thread is not blocked in a library function, its lock-free execution shall complete. That at least one of several concurrent lock-free executions completes is a *should*, because load-linked and store-conditional hardware can, in principle, make threads keep invalidating each other.

Whether a given `std::atomic<T>` is lock-free is up to the implementation. `is_always_lock_free` answers at compile time, `is_lock_free()` at run time, and only `std::atomic_flag` is guaranteed lock-free; C++20 added the aliases `std::atomic_signed_lock_free` and `std::atomic_unsigned_lock_free` for integer types that are. Results vary even on one machine. For a 16-byte struct on this page's arm64 test machine, Clang 21 reported `std::atomic` as always lock-free, while GCC 16 reported it as not lock-free and routed it through libatomic.

## CAS loops and the Treiber stack

The Treiber stack is a singly linked list whose head is an atomic pointer. Push links a new node in front of the current head and tries to swing the head to it. Pop reads the head and tries to swing it to the head's successor.

```cpp
#include <atomic>
#include <optional>
#include <utility>

template <class T>
class TreiberStack {
  struct Node { T value; Node* next; };
  std::atomic<Node*> head_{nullptr};

public:
  void push(T v) {
    Node* n = new Node{std::move(v), head_.load(std::memory_order_relaxed)};
    // On failure, n->next is overwritten with the current head and we retry.
    while (!head_.compare_exchange_weak(n->next, n,
                                        std::memory_order_release,
                                        std::memory_order_relaxed)) {
    }
  }

  std::optional<T> pop() {            // broken under concurrency: see below
    Node* old = head_.load(std::memory_order_acquire);
    while (old && !head_.compare_exchange_weak(old, old->next,
                                               std::memory_order_acquire,
                                               std::memory_order_acquire)) {
    }
    if (!old) return std::nullopt;
    T v = std::move(old->value);
    delete old;                       // another popper may still be reading old->next
    return v;
  }
};
```

Push is correct as written. The node is private until the CAS publishes it, so the plain writes to `value` and `next` cannot race, and passing `n->next` as the expected value means a failed CAS refreshes it for free. Using `compare_exchange_weak` is right because the loop recomputes everything anyway, so a spurious failure costs one more iteration.

Pop is not correct, and the bug is not subtle once you look at the line that reads `old->next`. Between loading `old` and reading its `next` field, another thread can pop the same node and delete it. The first thread then reads freed memory, which is undefined behavior whether or not its CAS would later fail.

## The ABA problem

Even if nodes are never freed but are recycled through a free list, pop can corrupt the stack. The CAS compares only the pointer value, and a pointer value can come back.

```text
head -> A -> B -> C

T1: old = A, next = B          (then T1 is preempted)
T2: pop A, pop B, push A       (A is reused; B is gone)
    head -> A -> C
T1: CAS(head, A -> B) succeeds, because head is A again
    head -> B                  (B is not in the stack any more; C is lost)
```

This is the ABA problem: the value went from A to B and back to A, and a single-word CAS cannot tell. With node recycling there is also a data race, because T2's push writes `A->next` while T1 reads it, so the program has undefined behavior before the CAS even runs, unless `next` is itself atomic.

> **Pitfall.** ABA and unsafe reclamation are two different problems that happen to share a cause. A version tag stops the wrong CAS from succeeding, but it does nothing about T1 dereferencing a node that has already been returned to the allocator. Most real fixes solve reclamation, and ABA disappears with it because a node cannot be reused while anyone can still see it.

## Safe memory reclamation

**Tagged pointers.** Pair the pointer with a counter in one atomic word and increment the counter on every successful update. The CAS now fails if anything happened in between, even if the pointer came back. On 64-bit targets this needs a double-width CAS, such as `cmpxchg16b` on x86-64 or `casp` on Armv8.1, or spare pointer bits; whether `std::atomic` of a 16-byte struct is lock-free is implementation-specific. Tags only solve ABA, so the nodes must live in memory that is never returned to the operating system.

```cpp
#include <atomic>
#include <cstdint>

struct Node { int value; Node* next; };
struct Tagged { Node* ptr; std::uintptr_t tag; };   // 16 bytes on a 64-bit target

std::atomic<Tagged> head{Tagged{nullptr, 0}};

Node* pop() {
  Tagged old = head.load(std::memory_order_acquire);
  while (old.ptr) {
    Tagged desired{old.ptr->next, old.tag + 1};      // every successful pop bumps the tag
    if (head.compare_exchange_weak(old, desired, std::memory_order_acquire,
                                   std::memory_order_acquire))
      return old.ptr;                                // caller must not free it to the OS
  }
  return nullptr;
}
```

**Hazard pointers.** Before dereferencing a shared pointer, a thread publishes it in a per-thread slot that every other thread can read, then re-reads the source to confirm it has not changed. A thread that unlinks a node does not delete it; it retires it, and retired nodes are freed only once no hazard slot holds their address. The publish and the re-check need sequentially consistent ordering, or an equivalent fence, so that the retiring thread is guaranteed to see the hazard.

**RCU and epochs.** Readers announce only that they are inside a read-side critical section, which can be almost free. A writer unlinks the old version and waits for a grace period, after which every reader that could have seen it has left, and then frees it. Epoch-based reclamation is the same idea with explicit global epoch counters. Reads become very cheap; the cost is that one stalled reader delays all reclamation.

C++26 standardizes both of the last two in `<hazard_pointer>` and `<rcu>`, covered in hazard-pointers-and-rcu.

**`std::atomic<std::shared_ptr<T>>`.** Since C++20 the reference count itself solves reclamation: a popper holding a `shared_ptr` copy of the head keeps that node alive, so it cannot be freed or reused underneath it, and ABA cannot occur.

```cpp
#include <atomic>
#include <memory>
#include <optional>

template <class T>
class SharedStack {
  struct Node { T value; std::shared_ptr<Node> next; };
  std::atomic<std::shared_ptr<Node>> head_;

public:
  void push(T v) {
    auto n = std::make_shared<Node>(std::move(v), head_.load());
    while (!head_.compare_exchange_weak(n->next, n)) {}
  }
  std::optional<T> pop() {
    std::shared_ptr<Node> old = head_.load();       // our reference keeps *old alive
    while (old && !head_.compare_exchange_weak(old, old->next)) {}
    if (!old) return std::nullopt;
    return std::move(old->value);
  }
};
```

It is simple and correct, but not necessarily lock-free: libstdc++ in GCC 16 reports `is_lock_free()` as false, and Clang 21's libc++ does not yet provide the specialization at all. Destroying a long chain of such nodes is also recursive and can overflow the stack.

## Memory orders in a CAS loop

A CAS takes two orders: one for success, when it is a read-modify-write, and one for failure, when it is only a load. Pick each by asking what the thread does next with what it read.

In push, success must be `release`, so that a popper's acquire sees the node's contents; failure can be `relaxed`, because the reloaded head is only stored into the private node. In pop, success needs `acquire` to read the value that push published. Failure also needs `acquire`, because the loop immediately dereferences the reloaded pointer to read `next`. Writing `relaxed` there is a classic bug that works on x86 and fails on Arm.

The failure order may not be `release` or `acq_rel`, since a failed CAS writes nothing; violating that precondition is undefined behavior. Until C++17 it also could not be stronger than the success order. P0418 removed that restriction, so success `relaxed` with failure `acquire` is valid today. If you pass only one order, the failure order is derived from it: `acq_rel` becomes `acquire`, `release` becomes `relaxed`, and the others stay as they are.

> **Pitfall.** GCC 16 still warns with `-Winvalid-memory-model` that a failure order "cannot be stronger than success". The warning reflects the pre-C++17 rule. The program is valid; the warning is a reason to check your orders, not proof of a bug.

## Contention, false sharing and linearizability

Lock-free is a progress property, not a speed property. Under heavy contention every thread hammers the same cache line, each failed CAS still has to take the line exclusively, and throughput can collapse below that of a mutex, which lets one thread run a batch of operations while the others sleep. Node-based structures also allocate on every push, and the reclamation scheme adds work to every access: a hazard pointer costs a sequentially consistent store per dereference. A sharded design, a per-thread buffer, or a plain `std::mutex` around a `std::vector` often wins.

False sharing makes it worse. Two atomics that are logically independent but share a cache line, such as a queue's head and tail indices, interfere as if they were one variable. This is a performance problem, not a correctness one: separate objects are separate memory locations and never race. Pad hot atomics apart with `alignas(std::hardware_destructive_interference_size)`, as described in atomics-and-memory-ordering.

The correctness criterion for a concurrent object is usually **linearizability**: every operation appears to take effect at a single instant between its call and its return, so the history is equivalent to some sequential history that respects real-time order. For the Treiber stack, the linearization point of a successful push or pop is its successful CAS, and of a pop that finds the stack empty, the load that read null. The C++ standard does not define linearizability. It gives you happens-before and the single total order of `seq_cst` operations, and a linearizability argument is built on top of those.

## What to remember

- Lock-free means some thread always progresses; wait-free means every thread does. CAS retry loops are lock-free, not wait-free.
- The standard requires only obstruction-freedom from lock-free atomics and merely encourages more; only `atomic_flag` is guaranteed lock-free.
- In a Treiber pop, reading `old->next` after another thread freed `old` is undefined behavior before ABA even arises.
- ABA is a CAS succeeding because a value came back; version tags fix ABA but not reclamation.
- Hazard pointers, RCU and epochs fix reclamation by delaying frees until no reader can hold the pointer; C++26 standardizes the first two.
- `atomic<shared_ptr>` avoids ABA through reference counting but is not lock-free in libstdc++.
- Choose the failure order by what you do with the reloaded value; it may not be `release` or `acq_rel`, and since C++17 it may be stronger than the success order.
- Lock-free structures can be slower than a mutex under contention; pad independent hot atomics to avoid false sharing.

## Concept Map Outline

- **Lock-free programming:** Replace locks with CAS retry loops; pay for it with ABA and memory reclamation.
  - **Progress guarantees:** Blocking, obstruction-free, lock-free and wait-free, from weakest to strongest.
    - **Lock-free:** Some thread always finishes; an individual thread may starve.
    - **Wait-free:** Every thread finishes in a bounded number of its own steps.
    - **What the standard requires:** [intro.progress] requires obstruction-freedom and only encourages lock-freedom.
    - **atomic_flag:** The only type guaranteed lock-free; ask is_always_lock_free for others.
  - **Treiber stack:** A linked list with an atomic head, updated by CAS loops.
    - **Push:** Link the private node to the head, CAS the head to it; a failed CAS refreshes next.
    - **Pop:** CAS the head to head->next; reading next of a freed node is UB.
    - **compare_exchange_weak:** Right inside a retry loop, since spurious failure costs one iteration.
  - **ABA problem:** A CAS succeeds because the pointer value came back, though the structure changed.
    - **Recycled node:** Pop A, pop B, push A again: a stale CAS installs the removed B.
    - **Tagged pointers:** A counter beside the pointer, updated by double-width CAS, defeats ABA.
    - **Not reclamation:** Tags stop the wrong CAS but not a dereference of freed memory.
  - **Safe reclamation:** Delay freeing a node until no thread can still hold a pointer to it.
    - **Hazard pointers:** Publish the pointer before use; retired nodes are freed when no slot holds them.
    - **RCU and epochs:** Cheap readers; writers wait for a grace period before freeing.
    - **atomic<shared_ptr>:** C++20; reference counts prevent reuse, but libstdc++'s is not lock-free.
    - **C++26 support:** <hazard_pointer> and <rcu> standardize the first two schemes.
  - **Memory orders in CAS:** Choose success and failure orders by what the thread does with the value.
    - **Push orders:** Success release to publish the node; failure relaxed.
    - **Pop orders:** Acquire on success and failure, because the reloaded pointer is dereferenced.
    - **Failure restrictions:** Never release or acq_rel; since C++17 it may be stronger than success.
  - **Performance:** Lock-free is a progress property, not a speed guarantee.
    - **Contention:** Every failed CAS still takes the cache line; a mutex can win.
    - **False sharing:** Independent atomics on one cache line slow each other but never race.
    - **Linearizability:** Each operation appears atomic at one point; for Treiber, the successful CAS.

## Standardese Quiz Questions

### Question 1 [warmup] ([atomics.types.operations])

What is the behavior of calling `try_set`?

```cpp
#include <atomic>

std::atomic<int> a{0};

bool try_set(int expected) {
  return a.compare_exchange_strong(expected, 1,
                                   std::memory_order_acq_rel,
                                   std::memory_order_release);
}
```

A. Well-defined: the failure order is silently strengthened to `acquire`
B. Ill-formed: the compiler must reject the failure order
C. Undefined behavior: the failure order may not be `release` or `acq_rel`
D. Well-defined: a failed CAS performs a release store of the old value

**Answer (C):** Undefined behavior: the failure order may not be `release` or `acq_rel`

**Why:** A failed compare-exchange is just a load, so a release failure order makes no sense, and the standard makes `failure` being `release` or `acq_rel` a precondition violation, which is undefined behavior. It is not ill-formed: the orders are ordinary function arguments, and GCC only warns with `-Winvalid-memory-model`. Some implementations happen to strengthen the order, but nothing guarantees it.

### Question 2 [warmup] ([atomics.flag], [atomics.lockfree])

Which of these types does the standard guarantee to be lock-free on every implementation?

A. `std::atomic<bool>`
B. `std::atomic_flag`
C. `std::atomic<int>`
D. `std::atomic<void*>`

**Answer (B):** `std::atomic_flag`

**Why:** `std::atomic_flag` is the only one of these guaranteed lock-free; it is the primitive from which an implementation can build locks for everything else. `std::atomic<int>`, `std::atomic<bool>` and `std::atomic<void*>` are lock-free on every mainstream platform, but the standard leaves it to the implementation, which is why `is_always_lock_free` and the `ATOMIC_..._LOCK_FREE` macros exist. C++20's `atomic_signed_lock_free` aliases are the other guaranteed option.

### Question 3 [warmup] ([atomics.types.operations])

Nodes are recycled through a free list instead of deleted, and `next` is atomic so that reusing a node is not a data race. Thread T1 runs `pop` on the stack `A -> B -> C`, reads `old = A` and `old->next == B`, and is preempted before its CAS. Thread T2 pops A, pops B, then pushes the recycled A, so the stack is `A -> C`. What happens when T1 resumes and its CAS runs?

```cpp
#include <atomic>

struct Node { int value; std::atomic<Node*> next; };
std::atomic<Node*> head;

Node* pop() {                              // assumes the stack is not empty
  Node* old = head.load(std::memory_order_acquire);
  Node* next = old->next.load();           // T1 is preempted here
  head.compare_exchange_strong(old, next);
  return old;
}
```

A. The CAS fails because the stack changed, and T1 retries
B. The CAS succeeds and makes the removed node B the head, losing C
C. The CAS succeeds and correctly leaves `C` as the head
D. The CAS blocks until T2's operations are complete

**Answer (B):** The CAS succeeds and makes the removed node B the head, losing C

**Why:** A compare-and-swap compares only the bits of the head pointer, and the head holds A again, so T1's CAS succeeds and installs its stale `next`, B, as the new head. B was popped and C is no longer reachable. This is the ABA problem: the value went from A to something else and back to A, and the CAS cannot tell. A version tag or a reclamation scheme that prevents reuse is needed to fix it.

### Question 4 [tricky] ([intro.memory], [intro.races])

Two threads run at the same time, one calling `left()` and the other `right()`, with no synchronization. What does the standard say?

```cpp
struct Counters {
  int a = 0;
  int b = 0;    // almost certainly on the same cache line as a
};

Counters c;

void left()  { for (int i = 0; i < 1000000; ++i) ++c.a; }
void right() { for (int i = 0; i < 1000000; ++i) ++c.b; }
```

A. It is a data race, so the behavior is undefined
B. It is not a data race, but each counter may lose increments to the other thread
C. It is not a data race; sharing a cache line can only affect performance
D. It is implementation-defined, depending on the cache line size

**Answer (C):** It is not a data race; sharing a cache line can only affect performance

**Why:** `a` and `b` are separate memory locations, so the two threads never access the same location and there is no data race. Each thread's counter ends at exactly one million. Sharing a cache line causes false sharing, which can make both loops much slower, but the memory model is defined in terms of memory locations, not cache lines. Adjacent bit-fields would be different, because they share one memory location.

### Question 5 [tricky] ([atomics.types.operations])

In C++17 and later, is this call well-defined?

```cpp
#include <atomic>

std::atomic<int> state{0};

bool claim(int expected) {
  return state.compare_exchange_strong(expected, 1,
                                       std::memory_order_relaxed,
                                       std::memory_order_acquire);
}
```

A. Yes: since C++17 the failure order may be stronger than the success order
B. No: the failure order may never be stronger than the success order
C. No: `relaxed` is not allowed as a success order for compare-exchange
D. It is well-defined only for `compare_exchange_weak`

**Answer (A):** Yes: since C++17 the failure order may be stronger than the success order

**Why:** Before C++17, the failure order could not be stronger than the success order. P0418, adopted for C++17, removed that rule, so the only remaining restriction is that failure is not `release` or `acq_rel`. GCC 16 still emits a `-Winvalid-memory-model` warning that reflects the old rule, which makes the second option tempting, but the call is valid.

### Question 6 [tricky] ([intro.progress])

Assuming `std::atomic<Node*>` is lock-free and only `push` and `pop` operations that each succeed with one CAS touch `head`, which progress guarantee does this `push` provide?

```cpp
#include <atomic>

struct Node { int value; Node* next; };
std::atomic<Node*> head{nullptr};

void push(Node* n) {
  n->next = head.load(std::memory_order_relaxed);
  while (!head.compare_exchange_strong(n->next, n,
                                       std::memory_order_release,
                                       std::memory_order_relaxed)) {
  }
}
```

A. Wait-free: every call finishes in a bounded number of steps
B. Blocking: a preempted thread can stop all others
C. Lock-free but not wait-free: some thread always finishes, but one thread can keep losing
D. Not even obstruction-free

**Answer (C):** Lock-free but not wait-free: some thread always finishes, but one thread can keep losing

**Why:** A strong CAS fails only because another thread changed `head`, which means another push or pop succeeded, so the system as a whole always makes progress. Nothing bounds how often one particular thread loses, so a thread can starve, which rules out wait-free. No thread ever waits for another to release anything, so it is not blocking. Whether the hardware CAS itself always lets someone win is the implementation's lock-free promise, which the standard only encourages.

### Question 7 [standardese] ([intro.progress])

What does [intro.progress] *require* of executions of lock-free atomic operations?

A. Every lock-free execution completes in a bounded number of steps
B. If only one thread is not blocked in a standard library function, its lock-free execution completes; that one of several concurrent executions completes is only encouraged
C. At least one of several concurrent lock-free executions must complete
D. Nothing: lock-freedom is a non-normative note

**Answer (B):** If only one thread is not blocked in a standard library function, its lock-free execution completes; that one of several concurrent executions completes is only encouraged

**Why:** The normative requirement is the obstruction-free property: a lock-free execution in the only thread that is not blocked shall complete. The stronger property that at least one of several concurrent lock-free executions completes is stated with *should*, because load-linked and store-conditional hardware can let threads repeatedly invalidate each other. The first option is wait-freedom, which the standard never promises.

### Question 8 [standardese] ([atomics.types.operations])

`ok` is `false` after this call. What does the standard guarantee about `e`?

```cpp
#include <atomic>

std::atomic<int> a{5};

void f() {
  int e = 5;
  bool ok = a.compare_exchange_weak(e, 6);
  (void)ok;
}
```

A. `e` is unchanged, because a failed CAS writes nothing
B. `e` holds the value read from `a`, which may still be 5 if the failure was spurious
C. `e` holds a value different from 5
D. `e` is indeterminate

**Answer (B):** `e` holds the value read from `a`, which may still be 5 if the failure was spurious

**Why:** On failure, compare-exchange atomically loads the current value into `expected`. `compare_exchange_weak` may also fail spuriously even when the values were equal, so `e` can still be 5. Only `compare_exchange_strong` guarantees that a failure means the values really differed, which is what the third option assumes. That is why `weak` belongs inside a retry loop.

# Parallel algorithms and execution policies

> Passing an execution policy to a standard algorithm grants the library permission to run your callbacks on several threads, interleaved within one thread, or both. This page explains what each policy permits, what that forbids in your code, why reduce is not accumulate, and what actually runs in parallel with GCC and Clang today.

- **Source:** C++ Atlas (https://cppatlas.com/topics/parallel-algorithms-and-execution-policies)
- **Track:** Concurrency
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [execpol] (https://eel.is/c++draft/execpol), [algorithms.parallel.defns] (https://eel.is/c++draft/algorithms.parallel.defns), [algorithms.parallel.user] (https://eel.is/c++draft/algorithms.parallel.user), [algorithms.parallel.exec] (https://eel.is/c++draft/algorithms.parallel.exec), [algorithms.parallel.exceptions] (https://eel.is/c++draft/algorithms.parallel.exceptions), [algorithms.parallel.overloads] (https://eel.is/c++draft/algorithms.parallel.overloads), [numerics.defns] (https://eel.is/c++draft/numerics.defns), [reduce] (https://eel.is/c++draft/reduce), [transform.reduce] (https://eel.is/c++draft/transform.reduce), [accumulate] (https://eel.is/c++draft/accumulate)
- **cppreference links:** [Execution policy types](https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t), [Execution policy objects](https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag), [std::reduce](https://en.cppreference.com/w/cpp/algorithm/reduce), [std::transform_reduce](https://en.cppreference.com/w/cpp/algorithm/transform_reduce), [std::accumulate](https://en.cppreference.com/w/cpp/algorithm/accumulate), [Algorithms library](https://en.cppreference.com/w/cpp/algorithm)
- **Prerequisites:** algorithms, threads-and-jthread, atomics-and-memory-ordering, lambdas

## The one idea

An execution policy is not an instruction to parallelize. It is a permission slip. Passing `std::execution::par` to `std::sort` tells the library that it *may* run the comparisons on several threads, and in exchange you promise that your code is safe if it does. The library is free to run everything sequentially, and with one popular standard library on one popular platform, it silently does. What changes for certain is the contract: your callbacks lose ordering guarantees, and an exception escaping one of them ends the program.

> **Mental model.** The policy describes what the library is allowed to do to your function objects, and therefore what your function objects must tolerate. Choose the weakest permission your code can survive, and then check whether your toolchain uses it.

## The four policies

The policies live in `<execution>`. Each is an object of a distinct type, and `std::is_execution_policy_v<T>` identifies them. C++17 introduced three; C++20 added `unseq`.

| Policy | Threads | Within one thread |
|---|---|---|
| `seq` (`sequenced_policy`) | only the calling thread | indeterminately sequenced, never interleaved |
| `par` (`parallel_policy`) | calling thread or library-created threads | indeterminately sequenced |
| `par_unseq` (`parallel_unsequenced_policy`) | any threads the library chooses | unsequenced, may be interleaved |
| `unseq` (`unsequenced_policy`, C++20) | only the calling thread | unsequenced, may be interleaved |

*Indeterminately sequenced* means that two calls on the same thread do not overlap, though their order is unspecified. *Unsequenced* means they may overlap: the library may vectorize, starting the bodies of several invocations before finishing any of them, so that four calls become one SIMD loop iteration.

Even `seq` is not the same as calling the algorithm without a policy. `std::for_each(first, last, f)` applies `f` in order from `first` to `last`, while `std::for_each(std::execution::seq, first, last, f)` only promises that each call happens on the calling thread, in an unspecified order. The policy overloads also require forward iterators, change the exception rules described below, and `for_each` with a policy returns `void` rather than the function object.

## Element access functions and data races

[algorithms.parallel.defns] calls the functions an algorithm invokes on your behalf **element access functions**: iterator operations, operations on the elements that the algorithm's specification requires, such as comparison or assignment, and your function objects. All the rules are about them.

Under `par`, it is your job to make sure that element access functions do not race with each other. The library does not add any synchronization between invocations.

```cpp
#include <algorithm>
#include <atomic>
#include <execution>
#include <vector>

void demo(const std::vector<int>& v) {
  std::vector<int> evens;
  std::for_each(std::execution::par, v.begin(), v.end(), [&](int x) {
    if (x % 2 == 0) evens.push_back(x);       // data race: undefined behavior
  });

  std::atomic<int> count{0};
  std::for_each(std::execution::par, v.begin(), v.end(), [&](int x) {
    if (x % 2 == 0) count.fetch_add(1, std::memory_order_relaxed);   // fine
  });
}
```

Blocking synchronization, such as a `std::mutex`, is allowed under `par`, but waiting for something that another element access function must do is not safe. The threads the library creates only promise *parallel forward progress*: an invocation that has not started may not start until yours finishes, so a spin-wait on it can hang forever.

Under `par_unseq` and `unseq`, interleaving on one thread rules out locking altogether. If two invocations on the same thread both reach `lock()`, the second blocks waiting for the first, which cannot continue because they are the same thread. The standard captures this by calling functions that synchronize with other invocations, such as mutex locking and unlocking, **vectorization-unsafe**, and forbids calling them from element access functions under the unsequenced policies. Memory allocation and deallocation are explicitly exempted.

> **Standardese.** [algorithms.parallel.exec] says element access functions invoked with `parallel_unsequenced_policy` may execute unordered in unspecified threads and are unsequenced with respect to one another within each thread, and that vectorization-unsafe standard library functions may not be invoked by user code called from such an algorithm. The same restriction applies to `unsequenced_policy`.

## Exceptions call std::terminate

With any of the four standard policies, if an element access function exits via an uncaught exception, `std::terminate` is called. This includes `seq`. A `try` block around the algorithm call never sees the exception. The one exception the algorithm itself can throw is `std::bad_alloc`, when it cannot get temporary memory needed for parallelization.

```cpp
#include <algorithm>
#include <execution>
#include <stdexcept>
#include <vector>

void demo(std::vector<int>& v) {
  try {
    std::for_each(std::execution::seq, v.begin(), v.end(), [](int) {
      throw std::runtime_error("boom");      // std::terminate is called
    });
  } catch (...) {
    // never reached
  }
}
```

The Parallelism TS that preceded C++17 collected exceptions into an `exception_list`; the standard dropped that design. Both libstdc++ and libc++ call `std::terminate` on this page's machine, including libstdc++ when it runs the algorithm serially. If your callbacks can throw, catch inside the lambda and record the failure, or use the non-policy overload.

## reduce is not accumulate

`std::accumulate` is a left fold: it computes `((init + a) + b) + c` in exactly that order. It has no policy overload, because a left fold cannot be split. `std::reduce`, added in C++17, computes a **generalized sum**: [numerics.defns] lets it group the operands in any way and reorder them in any way. The result equals the left fold only if the operation is associative and commutative over the values involved.

```cpp
#include <functional>
#include <numeric>
#include <vector>

int demo() {
  std::vector<int> v{1, 2, 3};
  int a = std::accumulate(v.begin(), v.end(), 10, std::minus<>{});  // ((10-1)-2)-3 == 4
  int r = std::reduce(v.begin(), v.end(), 10, std::minus<>{});      // unspecified result
  return a + r;
}
```

That freedom applies even without a policy argument, and implementations use it. Summing ten million random `float` values on this page's machine, `std::accumulate` returned about 4.9909e12, libstdc++'s sequential `std::reduce` returned 5.0002e12 because it keeps several partial sums, and libc++'s `std::reduce(std::execution::par, ...)` returned 5.0001e12, while its sequential `reduce` matched `accumulate`. All of these results are valid. Floating-point addition is commutative but not associative, so a parallel floating-point reduction is not reproducible across libraries, thread counts or even runs.

The scans make a finer distinction. `std::inclusive_scan` and `std::exclusive_scan` use a *generalized noncommutative sum*: they may regroup but must keep the order, so their operation needs to be associative but not commutative. `std::partial_sum`, like `accumulate`, is strictly left to right and has no policy overload.

> **Pitfall.** The accumulator type of `reduce` and `accumulate` is the type of `init`, not the element type. `std::reduce(v.begin(), v.end(), 0)` over a `std::vector<double>` adds into an `int` and truncates at every step. Write `0.0`, or call the two-iterator overload, which uses a value-initialized element type.

`std::transform_reduce` fuses a transformation with a reduction, which is how you express an inner product, a count, or a sum of squares in parallel without an intermediate container. Its two-range form defaults to `std::plus<>` for the reduction and `std::multiplies<>` for the transformation, so it is the parallel replacement for `std::inner_product`. The same associativity and commutativity requirement applies to its reduction operation.

```cpp
#include <execution>
#include <functional>
#include <numeric>
#include <vector>

double dot(const std::vector<double>& a, const std::vector<double>& b) {
  return std::transform_reduce(std::execution::par, a.begin(), a.end(), b.begin(), 0.0);
}

long long sum_squares(const std::vector<int>& v) {
  return std::transform_reduce(std::execution::par_unseq, v.begin(), v.end(), 0LL,
                               std::plus<>{}, [](int x) { return 1LL * x * x; });
}
```

## Iterator requirements and missing overloads

Every policy overload takes forward iterators, even where the non-policy version accepts input or output iterators. A parallel algorithm must be able to split the range and visit parts of it more than once, which a single-pass `std::istream_iterator` cannot support. Passing one violates the algorithm's requirements; GCC 16 compiled such a call without complaint, so do not rely on a diagnostic.

Many algorithms have no policy overload at all:

- numeric folds with a fixed order: `accumulate`, `inner_product`, `partial_sum`, and also `iota`;
- binary searches on sorted ranges: `lower_bound`, `upper_bound`, `equal_range`, `binary_search`;
- heap operations `push_heap`, `pop_heap`, `make_heap` and `sort_heap`, although `is_heap` and `is_heap_until` have one;
- `next_permutation`, `prev_permutation`, `shuffle`, `sample`, `copy_backward` and `move_backward`;
- every algorithm in `std::ranges`, which in C++23 accept no policy argument.

Writing `std::accumulate(std::execution::par, first, last, 0)` is simply ill-formed, because no overload matches. The replacements are `reduce`, `transform_reduce`, `inclusive_scan` and `exclusive_scan`.

## What actually runs in parallel

The standard specifies permissions, so a library that ignores the policy is conforming. What happens in practice depends on the library, and on this page's arm64 macOS machine the results were as follows.

**libstdc++ (GCC 16).** The parallel algorithms come from Intel's PSTL code and need oneTBB for real threads. At configuration time, libstdc++ checks `__has_include(<tbb/tbb.h>)`; if the header is found, it selects the TBB backend and you must link with `-ltbb`. If it is not found, it quietly selects a serial backend. TBB was not installed on the test machine, so `std::for_each(std::execution::par, ...)` over ten million elements ran entirely on the calling thread. It compiled without a warning and defined `__cpp_lib_parallel_algorithm`.

**libc++ (Clang 21).** The policies are still behind `-fexperimental-library`; without that flag, `std::execution::par` does not exist. With it, the macOS build uses a libdispatch backend, and the same loop ran on 11 different threads. libc++ implements only a subset of the policy overloads: `sort`, `stable_sort`, `for_each`, `transform`, `reduce`, `transform_reduce`, `find`, `count` and others compiled, but `inclusive_scan`, `nth_element`, `adjacent_find` and `partial_sort` with a policy did not.

MSVC's standard library has its own native implementation, which was not tested here. The practical lesson is to measure. Check thread usage and timing on your real toolchain, because a parallel call that silently runs serially still pays for the stricter contract, and a parallel call over a few thousand cheap elements can be slower than the serial loop because of task startup and the reduction step.

## What to remember

- A policy grants permission; the library may still run sequentially, and libstdc++ without TBB does.
- `seq` and `par` keep invocations on one thread from overlapping; `par_unseq` and `unseq` allow interleaving, so no locks inside them.
- Data races between element access functions are your responsibility; the library adds no synchronization.
- An exception escaping an element access function calls `std::terminate` under every standard policy, including `seq`.
- `reduce` may regroup and reorder, so the operation must be associative and commutative; floating-point results are not reproducible.
- `accumulate` is a strict left fold and has no policy overload; use `reduce` or `transform_reduce`.
- The type of `init` is the accumulator type, for `reduce` as for `accumulate`.
- Policy overloads need forward iterators; binary searches, heap operations, permutations and ranges algorithms have no policy overloads in C++23.
- With Clang's libc++, parallel algorithms need `-fexperimental-library` and only a subset is implemented.

## Concept Map Outline

- **Parallel algorithms:** An execution policy grants the library permission to parallelize; your callbacks must tolerate it.
  - **The four policies:** seq, par and par_unseq since C++17; unseq since C++20, all in <execution>.
    - **seq:** Calling thread only; invocations do not overlap but their order is unspecified.
    - **par:** Calling or library threads; invocations on one thread never overlap.
    - **par_unseq:** Any threads, and invocations may be interleaved within one thread.
    - **unseq:** Calling thread only, but invocations may be interleaved for vectorization.
  - **Element access functions:** Iterator operations, required element operations and your function objects.
    - **Data races:** The library adds no synchronization; races between invocations are UB.
    - **Locks under par:** Allowed, but never wait for another invocation that may not have started.
    - **Vectorization-unsafe:** Mutex locking is forbidden under par_unseq and unseq; allocation is exempt.
  - **Exceptions:** Policy overloads change error handling even with seq.
    - **std::terminate:** An exception escaping an element access function terminates under every standard policy.
    - **bad_alloc:** Thrown by the algorithm itself if it cannot get temporary memory.
    - **No exception_list:** The Parallelism TS design was not adopted into C++17.
  - **reduce vs accumulate:** A generalized sum may regroup and reorder; a left fold may not.
    - **Associative and commutative:** reduce and transform_reduce give the fold's result only for such operations.
    - **Scans:** inclusive_scan and exclusive_scan may regroup but keep order: associative is enough.
    - **Floating point:** Parallel or unrolled float sums differ between libraries and runs; all are valid.
    - **init type:** The accumulator has init's type, so 0 over doubles truncates.
    - **transform_reduce:** Fuses map and reduce; the two-range form is the parallel inner_product.
  - **Requirements and gaps:** Policy overloads need forward iterators and do not exist for every algorithm.
    - **Forward iterators:** Required even where the serial overload takes input iterators; not diagnosed by GCC.
    - **No policy overload:** accumulate, partial_sum, iota, binary searches, heap ops, permutations, ranges.
  - **Implementations:** Permission is not parallelism: measure on your toolchain.
    - **libstdc++:** Uses TBB if <tbb/tbb.h> is found, needing -ltbb; otherwise silently serial.
    - **libc++:** Needs -fexperimental-library; libdispatch on macOS; only a subset of overloads.
    - **Small inputs:** Task startup and the final combine can make par slower than a plain loop.

## Standardese Quiz Questions

### Question 1 [warmup] ([accumulate], [reduce])

Is this function well-formed?

```cpp
#include <execution>
#include <numeric>
#include <vector>

int total(const std::vector<int>& v) {
  return std::accumulate(std::execution::par, v.begin(), v.end(), 0);
}
```

A. Yes, and it runs in parallel if the library supports it
B. Yes, but the policy is ignored
C. Yes, but the result is unspecified because addition is reordered
D. No: `std::accumulate` has no execution-policy overload, so it is ill-formed

**Answer (D):** No: `std::accumulate` has no execution-policy overload, so it is ill-formed

**Why:** `std::accumulate` is defined as a strict left fold, which cannot be split across threads, so the standard gives it no policy overload. With four arguments the only candidate is `accumulate(first, last, init, op)`, and deduction fails because the first two arguments have different types. The parallel equivalent is `std::reduce(std::execution::par, v.begin(), v.end(), 0)`.

### Question 2 [warmup] ([algorithms.parallel.exec], [intro.races])

What is the behavior of this function, assuming `v` contains several even numbers?

```cpp
#include <algorithm>
#include <execution>
#include <vector>

std::vector<int> evens(const std::vector<int>& v) {
  std::vector<int> out;
  std::for_each(std::execution::par, v.begin(), v.end(), [&](int x) {
    if (x % 2 == 0) out.push_back(x);
  });
  return out;
}
```

A. Undefined behavior: concurrent `push_back` calls are a data race
B. Well-defined; only the order of `out` is unspecified
C. Well-defined: the library serializes calls that touch the same container
D. Well-defined, because a library may always run `par` sequentially

**Answer (A):** Undefined behavior: concurrent `push_back` calls are a data race

**Why:** Under `par`, element access functions may run concurrently on different threads, and the library adds no synchronization; avoiding data races is the caller's job. Two concurrent `push_back` calls on one vector are a data race, so the behavior is undefined. The last option is tempting because libstdc++ without TBB does run this serially, but the program's validity is judged against what the policy permits, not what one library happens to do.

### Question 3 [warmup] ([algorithms.parallel.exceptions], [execpol.seq])

What happens when this program runs?

```cpp
#include <algorithm>
#include <cstdio>
#include <execution>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3};
  try {
    std::for_each(std::execution::seq, v.begin(), v.end(),
                  [](int) { throw 42; });
  } catch (int) {
    std::puts("caught");
  }
}
```

A. It prints `caught`, because `seq` runs on the calling thread
B. An `std::exception_list` is thrown and not caught by `catch (int)`
C. `std::terminate` is called
D. The behavior is undefined

**Answer (C):** `std::terminate` is called

**Why:** For all four standard execution policies, an element access function that exits via an uncaught exception causes `std::terminate` to be called, and `seq` is no exception. The `try` block never sees the `int`. `exception_list` was the design of the Parallelism TS and is not in the standard. Without the policy argument, the exception would propagate and `caught` would be printed.

### Question 4 [tricky] ([reduce], [numerics.defns])

What does the standard say about the value returned?

```cpp
#include <functional>
#include <numeric>
#include <vector>

int f() {
  std::vector<int> v{1, 2, 3};
  return std::reduce(v.begin(), v.end(), 10, std::minus<>{});
}
```

A. It is 4, because no execution policy was given
B. It is unspecified, because `reduce` may regroup and reorder the operands
C. It is undefined behavior
D. It is ill-formed, because `std::minus` is not associative

**Answer (B):** It is unspecified, because `reduce` may regroup and reorder the operands

**Why:** `std::reduce` is specified as a generalized sum, which may group and order the operands, including `init`, arbitrarily, even without an execution policy. Subtraction is neither associative nor commutative, so different groupings give different values; the result is one of them, not undefined behavior. Nothing checks associativity at compile time. `std::accumulate` would guarantee `((10 - 1) - 2) - 3`, which is 4.

### Question 5 [tricky] ([algorithms.parallel.exec], [alg.foreach])

Does the standard guarantee that `order` is `{0, 1, 2, 3}` after this call?

```cpp
#include <algorithm>
#include <execution>
#include <vector>

std::vector<int> visit() {
  std::vector<int> idx{0, 1, 2, 3};
  std::vector<int> order;
  std::for_each(std::execution::seq, idx.begin(), idx.end(),
                [&](int i) { order.push_back(i); });
  return order;
}
```

A. Yes: `seq` means sequential, in order
B. No: each element is visited exactly once, but in an unspecified order
C. No: it is a data race, so the behavior is undefined
D. Yes, because `for_each` always proceeds from first to last

**Answer (B):** No: each element is visited exactly once, but in an unspecified order

**Why:** With `sequenced_policy`, all invocations happen on the calling thread and do not overlap, so there is no data race. But they are only indeterminately sequenced: the policy overload of `for_each` does not promise the first-to-last order that the non-policy overload does. Every implementation tested visits in order, but that is not guaranteed.

### Question 6 [tricky] ([algorithms.parallel.exec], [execpol.parunseq])

What is the behavior of this function?

```cpp
#include <algorithm>
#include <execution>
#include <mutex>
#include <vector>

int sum(const std::vector<int>& v) {
  std::mutex m;
  int total = 0;
  std::for_each(std::execution::par_unseq, v.begin(), v.end(), [&](int x) {
    std::lock_guard<std::mutex> lock(m);
    total += x;
  });
  return total;
}
```

A. Well-defined: the mutex prevents the data race
B. Guaranteed to deadlock
C. Undefined behavior: mutex locking is vectorization-unsafe and may not be called under `par_unseq`
D. Well-defined, but slower than a plain loop

**Answer (C):** Undefined behavior: mutex locking is vectorization-unsafe and may not be called under `par_unseq`

**Why:** Under `par_unseq`, invocations on the same thread may be interleaved, so one thread could start a second `lock()` before the first invocation unlocks, deadlocking against itself. The standard therefore forbids calling vectorization-unsafe functions, those that synchronize with another invocation, from element access functions under the unsequenced policies, and violating that is undefined behavior rather than a guaranteed deadlock. With `par`, the same code would be well-defined.

### Question 7 [standardese] ([execpol.unseq], [algorithms.parallel.exec])

Which policy permits element access functions to be interleaved, but only on the calling thread?

A. `std::execution::unseq`
B. `std::execution::seq`
C. `std::execution::par`
D. `std::execution::par_unseq`

**Answer (A):** `std::execution::unseq`

**Why:** `unsequenced_policy`, added in C++20, keeps all invocations on the calling thread but leaves them unsequenced with respect to each other, which allows vectorization. `par_unseq` also allows interleaving but adds multiple threads. `seq` and `par` both keep invocations on one thread indeterminately sequenced, meaning they never overlap.

### Question 8 [standardese] ([algorithms.parallel.exceptions])

A parallel algorithm needs temporary memory to parallelize and cannot obtain it. What does the standard say happens?

A. `std::terminate` is called
B. It throws `std::bad_alloc`
C. It falls back to sequential execution
D. The behavior is undefined

**Answer (B):** It throws `std::bad_alloc`

**Why:** [algorithms.parallel.exceptions] makes this the one exception a parallel algorithm itself may throw: if temporary memory resources required for parallelization are unavailable, it throws `std::bad_alloc`. The `std::terminate` rule applies to exceptions escaping element access functions, which are your callbacks and the element operations, not to the algorithm's own allocation.

---

# Track: Containers and strings

Memory layouts, iterator invalidation contracts, small-string optimization and non-owning views.

# Containers, memory layouts, and iterator invalidation

> How physical memory layouts dictate pointer, reference, and iterator invalidation across vector, deque, list, node-based maps, unordered hash tables, and C++23 flat_map.

- **Source:** C++ Atlas (https://cppatlas.com/topics/containers-and-iterator-invalidation)
- **Track:** Containers and strings
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [container.requirements] (https://eel.is/c++draft/container.requirements), [sequence.reqmts] (https://eel.is/c++draft/sequence.reqmts), [vector.modifiers] (https://eel.is/c++draft/vector.modifiers), [deque.modifiers] (https://eel.is/c++draft/deque.modifiers), [associative.reqmts] (https://eel.is/c++draft/associative.reqmts), [unord.req] (https://eel.is/c++draft/unord.req), [flat.map] (https://eel.is/c++draft/flat.map)
- **cppreference links:** [Containers library](https://en.cppreference.com/w/cpp/container), [std::vector](https://en.cppreference.com/w/cpp/container/vector), [std::deque](https://en.cppreference.com/w/cpp/container/deque), [std::list](https://en.cppreference.com/w/cpp/container/list), [std::map](https://en.cppreference.com/w/cpp/container/map), [std::unordered_map](https://en.cppreference.com/w/cpp/container/unordered_map), [std::flat_map](https://en.cppreference.com/w/cpp/container/flat_map), [std::vector<bool>](https://en.cppreference.com/w/cpp/container/vector_bool), [Container (named requirement)](https://en.cppreference.com/w/cpp/named_req/Container), [ContiguousContainer (named requirement)](https://en.cppreference.com/w/cpp/named_req/ContiguousContainer)
- **Prerequisites:** object-lifetime-and-storage, copy-and-move, smart-pointers-and-allocators

Iterator invalidation rules are not arbitrary library trivia—they fall straight out of each container's physical memory layout. Once you separate **pointer/reference stability** (whether elements stay at the same address) from **iterator stability** (whether traversal handles remain valid), you can predict invalidation guarantees on demand.

## Why physical layout predicts invalidation

Standard containers organize memory using four distinct strategies:

1. **Single contiguous buffer** (`std::vector`, `std::string`, `std::flat_map`): elements occupy adjacent slots in one heap array; growing capacity or shifting mid-array relocates elements in memory.
2. **Spine of fixed-size chunks** (`std::deque`): a central pointer table addresses fixed-size contiguous pages; appending at either end grows the spine without relocating existing elements.
3. **Linked heap nodes** (`std::list`, `std::forward_list`, `std::map`, `std::set`): every element lives inside its own heap node linked by pointers, so elements never relocate until erased.
4. **Bucket pointer array plus linked nodes** (`std::unordered_map`, `std::unordered_set`): elements live in individual heap nodes, while a contiguous bucket array indexes node chains.

> **Mental model.** Ask two questions before mutating a container: does the operation move existing elements to new addresses (invalidating pointers and references), and does it rewrite traversal metadata or sentinel slots (invalidating iterators)?

## Contiguous sequences and the reallocation cliff

In `std::vector`, `push_back` or `emplace_back` behaves differently depending on spare capacity. When `size() < capacity()`, appending writes into uninitialized tail storage and invalidates **only** `end()`; every existing iterator, pointer, and reference remains valid. When `size() == capacity()`, reallocation allocates a larger buffer, relocates elements via `std::move_if_noexcept`, frees the old array, and invalidates **all** iterators, pointers, and references. Remember that `std::move_if_noexcept` silently falls back to copying if a type's move constructor lacks `noexcept` and its copy constructor is available, preserving the strong exception guarantee.

Inserting or erasing in the middle of a `vector` without reallocation shifts trailing elements, invalidating iterators, pointers, and references at and after the modified index (plus `end()`). Beware the self-aliasing boundary in `[sequence.reqmts]`: single-element insertion or append from the same container (`v.push_back(v[0])`) is **guaranteed** to work even across reallocation, whereas inserting an iterator range from the same container (`v.insert(v.end(), v.begin(), v.end())`) is undefined behavior!

`std::vector<bool>` is a bit-packed space optimization rather than a true `ContiguousContainer`. Its `operator[]` returns a proxy `std::vector<bool>::reference` object instead of `bool&`, breaking reference binding and hiding a dangling pointer hazard.

> **Pitfall.** Writing `auto flag = flags[0];` on a `std::vector<bool>` deduces `flag` as a proxy `reference` rather than `bool`. If `flags` reallocates or leaves scope, inspecting `flag` later triggers use-after-free; always annotate `bool flag = flags[0];` when copying out a bit.

## Deque: chunked blocks and pointer stability

`std::deque` maintains a dynamic array of pointers (the spine) pointing to fixed-size contiguous blocks. Because pushing at either end allocates a new block when needed and only reallocates the **spine**—never copying existing elements—`std::deque` splits iterator validity from pointer and reference validity.

Under `[deque.modifiers]`, `push_back`, `push_front`, `emplace_back`, and `emplace_front` invalidate **all iterators** (because deque iterators cache pointers into the spine array), yet **preserve all pointers and references** to existing elements. Erasure at the boundaries is even more surgical: `pop_front` (or erasing the first element when `size() > 1`) invalidates only iterators and references to the erased element while leaving `end()` intact; `pop_back` (or erasing the last element) invalidates only handles to the erased element and `end()`. Inserting or erasing anywhere in the middle invalidates **all** iterators, pointers, and references to every element in the deque.

## Node containers, rehashing, and node handles

Tree and list containers (`std::list`, `std::forward_list`, `std::map`, `std::set`, `std::multimap`, `std::multiset`) allocate each element in a standalone node. Inserting elements **never** invalidates any iterator, pointer, or reference, and erasing invalidates **only** handles pointing to erased nodes.

Unordered hash containers (`std::unordered_map`, `std::unordered_set`) combine a dynamic bucket pointer array with linked element nodes. Erasing an element invalidates only handles to that erased node. When insertion pushes `size() > max_load_factor() * bucket_count()`, or when `rehash()` or `reserve()` expands the bucket array, hash tables rebuild their bucket table—invalidating **all iterators** while keeping every element pointer and reference valid!

C++17 introduced `extract()` and `merge()` via `node_type` handles, letting you unlink a node from one `map` or `unordered_map` and transplant it into another with zero key/value copies or moves. Extracting invalidates iterators to the removed element, while pointers and references to that element stay valid once reinserted. For safe conditional deletion, prefer C++20 `std::erase` and `std::erase_if` over manual loop-and-erase boilerplate.

> **Standardese.** Under `[unord.req]`, rehashing an unordered associative container invalidates all iterators and may reorder elements across buckets, yet references and pointers to elements in the container remain valid.

```cpp
#include <deque>
#include <flat_map>
#include <unordered_map>
#include <vector>

void invalidation_patterns() {
    std::vector<int> vec{1, 2, 3};
    vec.push_back(vec[0]); // Well-defined self-aliasing even if vec reallocates

    std::deque<int> dq{10, 20, 30};
    int& front_ref = dq.front();
    dq.push_back(40); // Invalidates ALL iterators, yet front_ref remains valid!
    (void)front_ref;

    std::unordered_map<int, int> umap{{1, 100}};
    int& mapped_ref = umap.at(1);
    umap.rehash(64); // Invalidates ALL iterators, yet mapped_ref remains valid!
    (void)mapped_ref;

    auto node = umap.extract(1); // Moves node without copying key or value
    std::unordered_map<int, int> dest;
    dest.insert(std::move(node));

    std::flat_map<int, int> fmap{{2, 20}, {1, 10}};
    std::erase_if(fmap, [](const auto& kv) { return kv.first == 1; });
}
```

## C++23 flat_map and flat_set trade-offs

C++23 `<flat_map>` and `<flat_set>` are container adaptors storing keys and mapped values in parallel sorted contiguous sequences (typically two `std::vector` objects) instead of heap-allocated tree nodes. Searching benefits from hardware prefetching and zero per-node pointer overhead, making lookup and iteration dramatically faster on small-to-medium maps.

That contiguous layout comes with two costs: single-element `insert` and `erase` run in O(N) time by shifting trailing entries, and—like `std::vector`—any insertion or erasure may invalidate **all** iterators, pointers, and references across the entire container.

> **Pitfall.** Replacing `std::map` with `std::flat_map` silently removes pointer and reference stability. Code that saves `&cache[key]` before inserting another key compiles identically and turns into a dangling pointer on the next insertion.

Invalidation behavior across the major standard container families lines up cleanly with their backing storage:

| Container | Insert / Push (No Growth) | Reallocate / Rehash | Erase |
| --- | --- | --- | --- |
| `std::vector` | Only `end()` on `push_back`; `[pos, end()]` on mid-insert | All iterators, pointers, and references | `[pos, end()]` |
| `std::deque` | At ends: all iterators; pointers & refs stay valid | Middle insert: all iterators, pointers, and refs | Ends: erased (+ `end()` at back); middle: all |
| `std::list` / `std::map` | None | N/A (node-based) | Erased element(s) only |
| `std::unordered_map` | None (unless load factor triggers rehash) | All iterators; pointers & refs stay valid | Erased element(s) only |
| `std::flat_map` | All iterators, pointers, and references | All iterators, pointers, and references | All iterators, pointers, and references |

## What to remember

- Distinguish **iterator** invalidation from **pointer and reference** invalidation: `std::deque::push_back` and `std::unordered_map::rehash` invalidate every iterator while keeping element addresses intact.
- In `std::vector`, reallocation invalidates everything, non-reallocating `push_back` invalidates only `end()`, and range `insert` from `[i, j)` into the same `vector` is undefined behavior even though `v.push_back(v[0])` is valid.
- Mark element move constructors `noexcept` so `std::vector` growth can move instead of copying via `std::move_if_noexcept`, and never capture `std::vector<bool>` elements with `auto`.
- Use `extract()` and `merge()` to relocate nodes between associative or unordered containers without copying keys or values, and reach for `std::erase_if` for safe predicate erasure.
- Treat C++23 `std::flat_map` and `std::flat_set` like `std::vector` for invalidation: any insertion or deletion can invalidate every iterator, pointer, and reference.

## Concept Map Outline

- **Containers & invalidation:** Physical memory layout directly predicts iterator, pointer, and reference invalidation.
  - **Contiguous buffers (vector):** One heap array maximizes cache locality while reallocation moves every element.
    - **Reallocation invalidates everything:** Growing capacity invalidates all iterators, pointers, and references.
    - **push_back within capacity:** When capacity suffices, appending invalidates only the past-the-end iterator.
    - **move_if_noexcept growth guard:** Missing noexcept on move constructors forces vector reallocation to copy.
    - **vector<bool> proxy reference:** operator[] returns a bit-proxy rather than bool&, dangling if deduced via auto.
  - **Chunked blocks (deque):** A spine of fixed pages lets ends grow without moving existing elements.
    - **Ends keep pointers & refs:** push_back and push_front preserve pointers and references to existing elements.
    - **Ends invalidate all iterators:** Spine reallocation invalidates every deque iterator on push_back or push_front.
    - **Middle insert or erase:** Modifying interior positions invalidates all iterators, pointers, and references.
  - **Node-based trees & lists:** Standalone heap nodes give complete stability across insertions and other erasures.
    - **Insertions never invalidate:** Adding nodes preserves all iterators, pointers, and element references.
    - **Erasures isolate removed node:** Erasing invalidates only iterators, pointers, and references to removed elements.
    - **C++17 extract & merge:** Transfers heap nodes between maps without copying or moving keys and values.
  - **Unordered hash tables:** Bucket array plus linked nodes separates iterator invalidation from node addresses.
    - **Rehash invalidates iterators only:** Growing bucket tables invalidates all iterators while keeping node pointers valid.
    - **Erasure preserves siblings:** Removing a bucket entry invalidates only handles to the erased element.
  - **C++23 flat_map & erasure:** Sorted parallel contiguous arrays trade node stability for cache speed.
    - **Any mutation invalidates handles:** Insertions and erasures shift contiguous slots, invalidating all pointers and iterators.
    - **Uniform C++20 std::erase_if:** Safely deletes matching elements across sequence and associative containers.

## Standardese Quiz Questions

### Question 1 [warmup] ([unord.req])

A std::unordered_map<int, Widget> triggers a rehash during emplace(). Which handles to existing elements remain valid?

A. All iterators, pointers, and references remain valid
B. All iterators are invalidated, while pointers and references to existing elements remain valid
C. Iterators remain valid, while pointers and references become dangling
D. All iterators, pointers, and references are invalidated

**Answer (B):** All iterators are invalidated, while pointers and references to existing elements remain valid

**Why:** Rehashing rebuilds the bucket array and may change element iteration order, invalidating every iterator ([unord.req]). Because elements live in individually allocated nodes that are relinked rather than relocated, pointers and references to elements stay valid.

### Question 2 [warmup] ([vector.modifiers])

A std::vector<int> holds 5 elements with capacity() == 16, and you call v.push_back(42);. Which existing handles are invalidated?

A. Only the past-the-end iterator (v.end()); existing element iterators, pointers, and references remain valid
B. All iterators, pointers, and references, including v.begin()
C. None at all, including v.end()
D. Only pointers and references to v.back()

**Answer (A):** Only the past-the-end iterator (v.end()); existing element iterators, pointers, and references remain valid

**Why:** Under [vector.modifiers], if no reallocation occurs (size() < capacity()), push_back invalidates only the past-the-end iterator (end()), leaving iterators, pointers, and references to all pre-existing elements valid.

### Question 3 [tricky] ([deque.modifiers])

In the snippet below, what happens to it and ref after dq.push_back(40) executes?

```cpp
std::deque<int> dq{10, 20, 30};
auto it = dq.begin();
int& ref = dq.front();
dq.push_back(40);
```

A. Both it and ref remain valid unless the spine reallocates
B. Both it and ref are guaranteed to be invalidated
C. it is invalidated (even if existing elements didn't move), whereas ref remains valid and still refers to 10
D. ref is invalidated, whereas it remains valid

**Answer (C):** it is invalidated (even if existing elements didn't move), whereas ref remains valid and still refers to 10

**Why:** Under [deque.modifiers], push_back and push_front invalidate all iterators to the deque (because deque iterators reference the spine array), yet have no effect on the validity of references or pointers to existing elements.

### Question 4 [tricky] ([vector.bool])

What happens when compiling and running the following snippet using std::vector<bool>?

```cpp
std::vector<bool> flags{true, false};
auto b = flags[0];
flags.assign(1000, false);
bool val = b;
```

A. Well-defined: val is true because auto deduced bool
B. Fails to compile because std::vector<bool>::operator[] returns void
C. Well-defined: flags.assign updates b to false automatically
D. Undefined behavior: auto b deduced a proxy std::vector<bool>::reference pointing into the old buffer freed by flags.assign(...)

**Answer (D):** Undefined behavior: auto b deduced a proxy std::vector<bool>::reference pointing into the old buffer freed by flags.assign(...)

**Why:** std::vector<bool> returns a bit-proxy reference class from operator[] rather than bool& ([vector.bool]). auto b = flags[0] stores that proxy pointing into flags's bit-word storage; once flags.assign(1000, false) reallocates, b dangles and bool val = b; exhibits undefined behavior.

### Question 5 [standardese] ([sequence.reqmts])

Compare v.push_back(v[0]); vs v.insert(v.end(), v.begin(), v.end()); on a non-empty std::vector<int> v at full capacity (v.size() == v.capacity()). What does the C++ standard say?

```cpp
std::vector<int> v{1, 2, 3};
v.shrink_to_fit();
// Case 1: v.push_back(v[0]);
// Case 2: v.insert(v.end(), v.begin(), v.end());
```

A. Both Case 1 and Case 2 are undefined behavior when v reallocates
B. Both Case 1 and Case 2 are guaranteed to succeed since C++11
C. Case 1 (v.push_back(v[0])) is well-defined and must handle self-aliasing, whereas Case 2 (v.insert with iterators into *this) is undefined behavior
D. Case 2 is well-defined, whereas Case 1 is undefined behavior

**Answer (C):** Case 1 (v.push_back(v[0])) is well-defined and must handle self-aliasing, whereas Case 2 (v.insert with iterators into *this) is undefined behavior

**Why:** Since C++11 ([sequence.reqmts]), single-element insertion/append (push_back(v[0]) or insert(pos, x)) must work even when x aliases an element inside *this during reallocation. Conversely, range insert(p, i, j) carries the precondition that i and j are not iterators into *this—making Case 2 undefined behavior.

### Question 6 [standardese] ([deque.modifiers])

According to [deque.modifiers], if dq has 4 elements and you call dq.pop_front(), which iterators and references are invalidated?

A. All iterators to dq, including dq.end(), plus references to the first element
B. Only iterators and references to the erased first element (dq.end() and all other elements' iterators/references remain valid)
C. All iterators and references to every element in dq
D. Only dq.end() and dq.begin()

**Answer (B):** Only iterators and references to the erased first element (dq.end() and all other elements' iterators/references remain valid)

**Why:** Under [deque.modifiers], erasing at the beginning (pop_front() or erase starting at begin(), provided the last element is not also erased) invalidates only iterators and references to the erased elements—preserving dq.end() and all other iterators and references. (By contrast, pop_back() also invalidates dq.end().)

# Sequence containers

> vector, deque, list, forward_list and array differ in one thing, where they put their elements, and every complexity bound, invalidation rule and exception guarantee follows from that layout. Learn the layouts and the rest can be derived.

- **Source:** C++ Atlas (https://cppatlas.com/topics/sequence-containers)
- **Track:** Containers and strings
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [sequence.reqmts] (https://eel.is/c++draft/sequence.reqmts), [vector.capacity] (https://eel.is/c++draft/vector.capacity), [vector.modifiers] (https://eel.is/c++draft/vector.modifiers), [deque.modifiers] (https://eel.is/c++draft/deque.modifiers), [list.ops] (https://eel.is/c++draft/list.ops), [forward.list] (https://eel.is/c++draft/forward.list), [vector.erasure] (https://eel.is/c++draft/vector.erasure)
- **cppreference links:** [std::vector](https://en.cppreference.com/w/cpp/container/vector), [std::deque](https://en.cppreference.com/w/cpp/container/deque), [std::list](https://en.cppreference.com/w/cpp/container/list), [std::forward_list](https://en.cppreference.com/w/cpp/container/forward_list), [std::array](https://en.cppreference.com/w/cpp/container/array), [std::vector::reserve](https://en.cppreference.com/w/cpp/container/vector/reserve), [std::list::splice](https://en.cppreference.com/w/cpp/container/list/splice)
- **Prerequisites:** copy-and-move, noexcept

## The one idea

A sequence container keeps its elements in an order you control, and the only real design choice is where the elements live. A `vector` keeps them in one contiguous block. A `deque` keeps them in several fixed-size blocks reached through an index. A `list` and a `forward_list` give every element its own node. A `std::array` keeps them inside the object itself.

Once you know the layout you can predict almost everything the standard promises: how long an operation takes, whether pointers to elements survive it, and what happens when an element's move constructor throws.

> **Mental model.** Ask two questions of any operation. Does it need to shift or reallocate elements? If so, it costs linear time and breaks references. Does it only relink or construct one element at an end? If so, it is cheap and the rest of the container is left alone.

```text
vector      [e0 e1 e2 e3 .. spare ..]        one block, capacity >= size
deque       map -> [e0 e1 e2] [e3 e4 e5] ... blocks, index of blocks
list        e0 <-> e1 <-> e2 <-> e3          node per element, two links
forward_list e0 -> e1 -> e2 -> e3            node per element, one link
array<T,N>  [e0 e1 e2]                       inside the object, no heap
```

The block structure of `deque` is an implementation technique rather than a requirement, but the guarantees the standard states can only be met by something like it.

## What each container guarantees

| Container | Element access | Insert or erase at end | At front | In the middle |
| --- | --- | --- | --- | --- |
| `vector` | random, contiguous | amortized constant | linear | linear |
| `deque` | random, not contiguous | constant | constant | linear |
| `list` | none by index | constant | constant | constant, given an iterator |
| `forward_list` | none by index | linear to find the end | constant | constant after an iterator |

`vector` and `array` are the contiguous ones: `&v[0]` plus an offset reaches every element, so `v.data()` can be handed to a C interface. `deque` is random access but not contiguous, so it has no `data()`. `list` and `forward_list` have only bidirectional and forward iterators.

`forward_list` has no `size()` at all. The standard leaves it out so the container costs no more than a hand-written singly linked list. It also has no `push_back` and no `insert`, only `insert_after` and `erase_after`, because a node cannot reach its predecessor.

## Growth, `reserve` and `shrink_to_fit`

`vector::push_back` is amortized constant time because capacity grows geometrically. The standard does not say what the factor is, only that `capacity()` is at least `size()` and that reallocation happens only when a larger size would exceed the capacity. Do not assume doubling.

`reserve(n)` raises capacity to at least `n`, and after it, insertions will not reallocate until the size would exceed `capacity()`. That is a guarantee you can build on: iterators and references stay valid across those insertions. It does not create elements.

```cpp
#include <vector>

void demo() {
  std::vector<int> v;
  v.reserve(100);
  // v.size() == 0 and v.capacity() >= 100, but v[0] is undefined behavior.
  v.push_back(1);          // no reallocation, whatever the growth policy is
  v.resize(10);            // this is what creates elements
  v.shrink_to_fit();       // a request: capacity() may stay larger
}
```

`shrink_to_fit` is explicitly a non-binding request. An implementation may ignore it, and if it does reallocate, everything is invalidated. If you must release the storage, destroy the vector or swap it with an empty one.

A `deque` has no `capacity`, `reserve` or `data`. `list` and `forward_list` have none of these either: there is nothing to reserve when every element is its own allocation.

## Reallocation and `noexcept` moves

When a `vector` runs out of room it allocates a new block and relocates the old elements. It must keep the strong exception guarantee for `push_back`: if something throws, the vector is as it was before. Moving elements out of the old block would break that, because a throwing move leaves some elements already stolen.

So the implementation uses `std::move_if_noexcept`. If the move constructor is `noexcept`, or the type cannot be copied, elements are moved. Otherwise they are copied, and the originals stay safe until the copy finishes.

```cpp
#include <cstdio>
#include <vector>

struct Slow {
  Slow() = default;
  Slow(const Slow&) { std::puts("copy"); }
  Slow(Slow&&) { std::puts("move"); }   // forgot noexcept: growth copies
};

struct Fast {
  Fast() = default;
  Fast(const Fast&) { std::puts("copy"); }
  Fast(Fast&&) noexcept { std::puts("move"); }  // growth moves
};
```

This is why a missing `noexcept` on a move constructor is a performance bug that no test fails on. The rule is covered in depth in the topic on `noexcept`. The standard requires the strong guarantee for a single `push_back` of a copyable type, and the mainstream implementations meet it with `move_if_noexcept`.

> **Pitfall.** A move-only type whose move constructor can throw is moved anyway, because there is no copy to fall back on. If that move throws during growth, the standard says the effects are unspecified.

## `emplace_back` versus `push_back`

`push_back(x)` takes an already-built element, copies or moves it into the new slot. `emplace_back(args...)` forwards its arguments to a constructor and builds the element in place. The saved temporary rarely matters for cheap types, but two differences are about correctness.

First, `emplace_back` can call an `explicit` constructor, where `push_back(3)` cannot convert an `int` into an explicit-constructible `P` and is rejected. That cuts both ways: `emplace_back` also makes it easy to construct something you did not mean to. Second, `emplace_back` returns a reference to the new element since C++17, so you can use the new element straight away.

```cpp
#include <string>
#include <vector>

struct P {
  explicit P(int);
};

void f(std::vector<P>& v, std::vector<std::string>& s) {
  v.emplace_back(1);        // OK: explicit constructor, called directly
  // v.push_back(1);        // ill-formed: needs an implicit conversion
  s.push_back("abc");       // builds a std::string temporary, then moves it
  s.emplace_back("abc");    // builds the std::string directly in the slot
}
```

The argument may even alias an element: `v.push_back(v[0])` is required to work, even when it reallocates, so implementations construct the new element before destroying the old block.

## `deque` and `list`: what stays put

`deque` keeps its element blocks where they are when you add at either end. The index of blocks may be rebuilt, so every iterator is invalidated, but no element moves, so references and pointers survive. Inserting or erasing in the middle shifts elements and invalidates everything.

```cpp
#include <deque>

void demo() {
  std::deque<int> d{1, 2, 3};
  int& r = d[1];
  d.push_front(0);
  d.push_back(4);
  r = 99;                   // OK: references survive end insertions
  // an iterator taken before the pushes would be invalid here
}
```

The full table of rules lives in the topic on iterator invalidation. A `list` is the extreme case: no element ever moves, so only iterators to the erased elements die. That also makes `splice` possible. `a.splice(pos, b, it)` relinks one node from `b` into `a` in constant time. No element is copied or destroyed, so references stay valid and iterators keep referring to the same elements, now as iterators into `a`.

```cpp
#include <list>

void demo() {
  std::list<int> a{1, 2, 3}, b{4, 5};
  auto it = a.begin();
  b.splice(b.end(), a, it);   // constant time; *it is still 1, now inside b
  b.splice(b.end(), a);       // moves everything left in a: also constant
}
```

Splicing a range `[first, last)` from a different list is linear in the length of the range, because the destination's `size()` must be updated and `list::size()` is constant time. Same list, constant.

`forward_list` has the matching operations with `_after` names: `splice_after`, `insert_after`, `erase_after`, and `before_begin()` to get a position before the first element. `merge`, `sort`, `reverse`, `remove` and `unique` are member functions on both list types, because the generic algorithms need random access or cannot relink nodes.

## Erasing and the C++20 and C++23 additions

Removing elements by value or predicate used to mean the erase-remove idiom: `v.erase(std::remove_if(...), v.end())`. C++20 added non-member `std::erase(c, value)` and `std::erase_if(c, pred)` for `vector`, `deque`, `list` and `forward_list`, and `erase_if` for the associative containers too. They return the number of removed elements. For `list` and `forward_list` they call the member `remove_if`, which relinks nodes; for `vector` and `deque` they do the erase-remove idiom.

```cpp
#include <vector>

void demo() {
  std::vector<int> v{1, 2, 3, 4, 5, 6};
  auto n = std::erase_if(v, [](int x) { return x % 2 == 0; });
  // n == 3, v == {1, 3, 5}
  (void)n;
}
```

C++23 added range-aware members. `insert_range(pos, rg)` inserts a whole range and returns an iterator to the first inserted element. `append_range(rg)` adds at the end and returns `void`. `assign_range` replaces the contents. `forward_list` has `insert_range_after` and `prepend_range` instead. They avoid the temporary container and let `vector` allocate once when the range's size is known. The inserted range must not overlap the container itself.

## Choosing

Start with `vector`; it wins more often than its complexity table suggests, because contiguous memory is friendly to caches and prefetchers. A `list` earns its place only when you need stable iterators and references through arbitrary insertion and removal, or constant-time `splice`. Reach for `deque` when you need both-end insertion with reference stability, a queue that grows at the back and shrinks from the front, or very large containers where reallocating one huge block hurts. Use `forward_list` only when per-element overhead of one pointer matters. Use `std::array` when the size is a compile-time constant; its details belong to the topic on `array`, `bitset` and `vector<bool>`.

> **Standardese.** [list.ops] says that after a splice, pointers and references to the moved elements refer to the same elements as members of the destination, and iterators keep referring to their elements but behave as iterators into the destination. [vector.capacity] says no reallocation takes place after `reserve` until an insertion would make the size exceed the capacity, and describes `shrink_to_fit` as a non-binding request.

## What to remember

- Layout decides everything: contiguous block, block index, one node per element, or inline storage.
- `vector` growth is amortized constant, with an unspecified factor; `reserve` creates capacity, not elements.
- `shrink_to_fit` and `reserve` beyond capacity can reallocate; only `reserve` gives a guarantee about later insertions.
- Growth moves elements only when their move is `noexcept` or they cannot be copied; otherwise it copies. Mark moves `noexcept`.
- `emplace_back` constructs in place and can call explicit constructors; `push_back` takes a finished element.
- `deque` end insertions invalidate iterators but not references; middle insertions invalidate both.
- `list::splice` moves nodes without touching elements, so iterators stay valid and now belong to the destination.
- `forward_list` has no `size()`, and its operations act after a position.
- C++20 `erase` and `erase_if` replace the erase-remove idiom; C++23 `insert_range` and `append_range` take whole ranges.
- Default to `vector`, and change only for a stated reason.

## Concept Map Outline

- **Sequence containers:** Five containers that differ in where elements live; guarantees follow from layout.
  - **Layouts:** Storage shape decides complexity, invalidation and exception behavior.
    - **vector:** One contiguous block with spare capacity; data() works.
    - **deque:** Fixed-size blocks behind an index; random access but not contiguous.
    - **list and forward_list:** One node per element; forward_list has no size() and only _after operations.
    - **array:** Elements live inside the object; fixed size, no allocation.
  - **Growth and capacity:** Only vector has capacity; the growth factor is unspecified.
    - **push_back amortized O(1):** Capacity grows geometrically, so appending is amortized constant time.
    - **reserve:** Raises capacity without creating elements; later insertions do not reallocate until capacity is exceeded.
    - **shrink_to_fit:** A non-binding request to drop spare capacity; the implementation may ignore it.
  - **Relocation on growth:** Growth must keep the strong guarantee for copyable types.
    - **move_if_noexcept:** Elements are moved only if their move is noexcept or they cannot be copied.
    - **Mark moves noexcept:** A missing noexcept silently turns reallocation into copying.
  - **Inserting elements:** Construction in place versus passing a finished object.
    - **emplace_back:** Forwards arguments to a constructor, including explicit ones, and returns a reference since C++17.
    - **push_back:** Copies or moves an existing element; cannot use an explicit conversion.
    - **insert_range, append_range:** C++23 range members; insert_range returns an iterator, append_range returns void.
  - **What stays put:** Which references and iterators survive common operations.
    - **deque end insertion:** Invalidates iterators but not references or pointers to existing elements.
    - **list::splice:** Relinks nodes in constant time; iterators stay valid and now belong to the destination.
  - **Erasing and choosing:** Removal helpers and a default pick.
    - **erase and erase_if:** C++20 non-member functions replace the erase-remove idiom and return the removed count.
    - **Default to vector:** Contiguous memory is cache friendly; switch only for a stated need such as stability or splice.

## Standardese Quiz Questions

### Question 1 [warmup] ([vector.erasure], [alg.remove])

In C++23, what does this program print?

```cpp
#include <iostream>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3, 4, 5, 6};
  auto n = std::erase_if(v, [](int x) { return x % 2 == 0; });
  std::cout << n << ' ' << v.size() << '\n';
}
```

A. 3 3
B. 3 6
C. 6 3
D. Undefined behavior

**Answer (A):** 3 3

**Why:** Since C++20, `std::erase_if` on a `vector` performs the erase-remove idiom for you and returns the number of elements it removed. Three even numbers go, so `n` is 3 and the size drops from 6 to 3. The tempting `3 6` imagines `std::remove_if` alone, which shuffles elements but leaves the size unchanged.

### Question 2 [warmup] ([vector.modifiers], [class.conv.ctor])

Which of the three calls is ill-formed?

```cpp
#include <vector>

struct P {
  explicit P(int);
};

void f(std::vector<P>& v) {
  v.emplace_back(1);  // (1)
  v.push_back(P(2));  // (2)
  v.push_back(3);     // (3)
}
```

A. None of them
B. Only (2)
C. Only (3)
D. (2) and (3)

**Answer (C):** Only (3)

**Why:** `emplace_back` forwards its arguments to a constructor call, so an explicit constructor is fine. `push_back(P(2))` passes an actual `P`. `push_back(3)` needs an implicit conversion from `int` to `P` to bind the `value_type` parameter, and an explicit constructor forbids that, so only (3) is rejected.

### Question 3 [warmup] ([vector.capacity], [sequence.reqmts])

What is the behavior of this program?

```cpp
#include <vector>

int main() {
  std::vector<int> v;
  v.reserve(10);
  v[0] = 1;
}
```

A. Well-formed; `v` now holds one element
B. Undefined behavior
C. Throws `std::out_of_range`
D. Well-formed; element 0 is written but `size()` stays 0

**Answer (B):** Undefined behavior

**Why:** `reserve` only allocates capacity; it creates no elements and leaves `size()` at 0. `operator[]` does no bounds check, and indexing at or past `size()` is undefined behavior, even though the storage exists. `at` would throw `std::out_of_range`, which is the tempting but wrong description of `operator[]`.

### Question 4 [tricky] ([deque.modifiers])

What does this program print?

```cpp
#include <deque>
#include <iostream>

int main() {
  std::deque<int> d{1, 2, 3};
  int& r = d[1];
  for (int i = 0; i < 1000; ++i) {
    d.push_back(i);
    d.push_front(-i);
  }
  r = 99;
  std::cout << d[1001] << '\n';
}
```

A. 2
B. Undefined behavior: the reference was invalidated
C. 99
D. Implementation-defined

**Answer (C):** 99

**Why:** Insertion at either end of a `deque` invalidates iterators but never references or pointers to existing elements. The original element 2 sits at index 1001 after 1000 `push_front` calls, and `r` still names it, so the write is well-defined and the program prints 99. The same program using an iterator instead of `r` would be undefined behavior, which is what makes the first option tempting.

### Question 5 [tricky] ([list.ops])

What does this program print?

```cpp
#include <iostream>
#include <iterator>
#include <list>

int main() {
  std::list<int> a{1, 2, 3}, b{4, 5};
  auto it = a.begin();
  b.splice(b.end(), a, it);
  std::cout << *it << ' ' << std::boolalpha
            << (std::next(it) == b.end()) << ' ' << a.size() << '\n';
}
```

A. Undefined behavior: `it` is invalidated by the splice
B. 1 true 2
C. 1 false 2
D. 4 true 2

**Answer (B):** 1 true 2

**Why:** `splice` relinks nodes without copying or destroying anything. Iterators to the moved element stay valid, keep referring to the same element, and now behave as iterators into `b`. The element 1 is the new last element of `b`, so `std::next(it)` equals `b.end()`, and `a` is left with two elements. The third option imagines `it` still belonging to `a`.

### Question 6 [tricky] ([vector.modifiers])

With libstdc++ or libc++, what does this program print after `grow`? (The standard only demands the strong exception guarantee; this is what both implementations do for a copyable type.)

```cpp
#include <cstdio>
#include <vector>

struct S {
  S() = default;
  S(const S&) { std::puts("copy"); }
  S(S&&) { std::puts("move"); }  // not noexcept
};

int main() {
  std::vector<S> v;
  v.reserve(4);
  while (v.size() < v.capacity()) v.emplace_back();
  std::puts("grow");
  v.emplace_back();
}
```

A. One `move` line for each old element
B. One `copy` line for each old element
C. Nothing; growth never touches the old elements
D. One `move` line, then the old elements are copied

**Answer (B):** One `copy` line for each old element

**Why:** To keep the strong guarantee, `vector` relocates with `std::move_if_noexcept`: elements are moved only if the move constructor is `noexcept` or the type cannot be copied. Here the move constructor may throw and a copy constructor exists, so every old element is copied, and the originals stay intact if a copy throws. Marking the move constructor `noexcept` would flip the output to `move`.

### Question 7 [standardese] ([forward.list], [container.reqmts])

Is this program well-formed in C++23?

```cpp
#include <forward_list>

int main() {
  std::forward_list<int> f{1, 2, 3};
  return static_cast<int>(f.size());
}
```

A. Well-formed; `size()` is linear time
B. Well-formed; `size()` is constant time
C. Ill-formed: `forward_list` has no `size()` member
D. Unspecified

**Answer (C):** Ill-formed: `forward_list` has no `size()` member

**Why:** `forward_list` is specified as a container that omits `size()`, so that it can keep the same space overhead as a hand-written singly linked list. Use `std::distance(f.begin(), f.end())` and accept the linear cost. `list`, by contrast, has a constant-time `size()` since C++11.

### Question 8 [standardese] ([vector.modifiers], [sequence.reqmts])

In C++23, what does this program print?

```cpp
#include <array>
#include <iostream>
#include <vector>

int main() {
  std::vector<int> v{1, 2};
  std::array<int, 2> a{8, 9};
  auto it = v.insert_range(v.begin(), a);
  std::cout << *it << ' ';
  v.append_range(a);
  std::cout << v.size() << '\n';
}
```

A. 1 6
B. Ill-formed: `insert_range` returns `void`
C. 9 6
D. 8 6

**Answer (D):** 8 6

**Why:** C++23 added range-aware members. `insert_range` returns an iterator to the first inserted element (the 8), and `append_range` returns `void`. The vector goes from 2 to 4 to 6 elements. Dereferencing `it` before the append matters, because a reallocation in `append_range` would invalidate it.

# Associative and unordered containers

> The ordered containers are sorted trees driven by a comparator, and the unordered ones are hash tables driven by a hash and an equality predicate. The rules for keys, complexity, rehashing and the many insertion functions all follow from those two designs.

- **Source:** C++ Atlas (https://cppatlas.com/topics/associative-and-unordered-containers)
- **Track:** Containers and strings
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [associative.reqmts] (https://eel.is/c++draft/associative.reqmts), [unord.req] (https://eel.is/c++draft/unord.req), [map.access] (https://eel.is/c++draft/map.access), [map.modifiers] (https://eel.is/c++draft/map.modifiers), [unord.hash] (https://eel.is/c++draft/unord.hash)
- **cppreference links:** [std::map](https://en.cppreference.com/w/cpp/container/map), [std::set](https://en.cppreference.com/w/cpp/container/set), [std::unordered_map](https://en.cppreference.com/w/cpp/container/unordered_map), [std::unordered_set](https://en.cppreference.com/w/cpp/container/unordered_set), [std::map::try_emplace](https://en.cppreference.com/w/cpp/container/map/try_emplace), [std::hash](https://en.cppreference.com/w/cpp/utility/hash), [std::unordered_map::rehash](https://en.cppreference.com/w/cpp/container/unordered_map/rehash)
- **Prerequisites:** sequence-containers

## The one idea

There are eight standard associative containers, and they are two designs wearing four hats each. `set`, `map`, `multiset` and `multimap` keep elements sorted by a comparator, and the logarithmic guarantees for lookup, insertion and erasure essentially force a balanced search tree. `unordered_set`, `unordered_map` and their multi versions keep elements in a hash table: lookup, insertion and erasure are constant on average and linear in the worst case.

Both designs are **node based**. Each element is its own allocation, which is why an element's address never changes while it is in the container, and why neither design has `capacity` or random access.

> **Mental model.** Ordered containers decide where a key goes with `<`, and two keys are the same key if neither is less than the other. Unordered containers decide with a hash and then `==`, and two keys are the same key if the equality predicate says so. Everything else, including what counts as a duplicate, comes from that choice.

## Ordered containers and the comparator

The comparator must be a strict weak ordering. In practice that means `comp(x, x)` is false, the relation is transitive, and "neither is less than the other" is an equivalence relation. The container never calls `==`. It calls the comparator in both directions, and two keys are the same key when `!comp(a, b) && !comp(b, a)`.

That is why a case-insensitive set is a one-line change, and why `std::less_equal` is a bug.

```cpp
#include <algorithm>
#include <cctype>
#include <set>
#include <string>

struct CaseLess {
  bool operator()(const std::string& a, const std::string& b) const {
    return std::lexicographical_compare(
        a.begin(), a.end(), b.begin(), b.end(),
        [](unsigned char x, unsigned char y) {
          return std::tolower(x) < std::tolower(y);
        });
  }
};

void demo() {
  std::set<std::string, CaseLess> names;
  names.insert("Ada");
  auto [it, ok] = names.insert("ADA");  // ok == false: equivalent to "Ada"
  // *it is still "Ada"
}
```

A comparator that is not a strict weak ordering, such as `<=`, breaks a precondition of the container and the behavior is undefined, even if one implementation happens to store two copies. A key type compared by pointer, such as `const char*`, is well-defined but orders by address, not by text.

Because the sort order is the structure, the stored key must never change. That is the reason for **key constness**: the value type of `map<K, V>` is `pair<const K, V>`, and the elements of a `set` are const. If you need to change a key, erase and reinsert, or use a node handle, which the topic on node handles covers along with transparent comparators for lookup without constructing a key.

Ordered containers also give you range queries that hash tables cannot. `lower_bound(k)` returns the first element not less than `k`, `upper_bound(k)` the first greater, and `equal_range(k)` the pair of them: the elements equivalent to `k`. Iteration visits elements in comparator order.

## Unordered containers: buckets, load factor and rehash

A hash table has an array of **buckets**. The hash of a key picks a bucket, and the equality predicate finds the key within it. The **load factor** is the average number of elements per bucket, `size() / bucket_count()`, and `max_load_factor()` is the limit, 1.0 by default. When an insertion would push the load factor above the limit, the container grows its bucket count and redistributes every element. That redistribution is a **rehash**.

```cpp
#include <cassert>
#include <unordered_set>

void demo() {
  std::unordered_set<int> s;
  s.reserve(1000);                 // buckets for 1000 elements at max_load_factor 1.0
  assert(s.bucket_count() >= 1000);
  for (int i = 0; i < 1000; ++i) s.insert(i);   // no rehash: reserved up front
}
```

`reserve(n)` is the unordered counterpart of `vector::reserve`: it is `rehash(ceil(n / max_load_factor()))`. `rehash(b)` sets the bucket count to at least `b` and at least what the current size needs. Both cost linear time on average.

The complexity bounds are averages. If many keys land in one bucket, whether by a poor hash or by an adversary, lookups degrade to linear. The standard guarantees constant time only on average and linear in the worst case.

The iteration order of an unordered container is unspecified, can differ between implementations, and can change after a rehash. Never depend on it.

**Stability across rehash** is where the node design pays off. A rehash invalidates all iterators, because iterators know about the bucket structure. It does not invalidate pointers or references to elements, because the nodes themselves are not touched. Insertion that does not trigger a rehash invalidates nothing.

## Hash requirements

The hash function must be consistent with the equality predicate: if two keys compare equal, their hashes must be equal. A hash and equality pair that violates this makes the behavior undefined, because the container will look in the wrong bucket. The hash must also return the same value for the same key within a program run.

`std::hash` has enabled specializations for the built-in arithmetic types, pointers, strings, string views, and several library types. It has none for `std::pair`, `std::tuple` or your own types, so such a key does not compile with the default hash. For a type you own, you may specialize `std::hash`, which is one of the few things the standard lets you add to `namespace std`:

```cpp
#include <cstddef>
#include <functional>
#include <unordered_map>

struct Point {
  int x, y;
  friend bool operator==(const Point&, const Point&) = default;
};

template <>
struct std::hash<Point> {
  std::size_t operator()(const Point& p) const noexcept {
    std::size_t h = std::hash<int>{}(p.x);
    return h ^ (std::hash<int>{}(p.y) + 0x9e3779b9 + (h << 6) + (h >> 2));
  }
};

std::unordered_map<Point, int> grid;   // OK: default Hash is std::hash<Point>
```

The standard provides no combiner for hashes, so the mixing step above is the usual hand-written pattern. Alternatively, pass a hash type as the container's second template argument and leave `std::hash` alone.

> **Pitfall.** Equality and hash must come from the same notion of "same key". If `operator==` ignores a field, the hash must ignore it too. A hash that includes a field the equality ignores breaks the rule above and is undefined behavior.

## Inserting and looking up

The two families share a family of insertion functions, and they differ in exactly two ways: what they do when the key already exists, and when they construct things.

```cpp
#include <map>
#include <string>
#include <utility>

struct NoDefault {
  explicit NoDefault(int v) : v(v) {}
  int v;
};

void demo() {
  std::map<std::string, int> m;
  m["a"] = 1;                      // inserts 0 if missing, then assigns
  int x = m["b"];                  // also inserts "b" -> 0; not a pure lookup
  m.insert({"c", 3});              // does nothing if "c" exists
  m.emplace("d", 4);               // may build a node first, then discard it
  m.try_emplace("e", 5);           // looks up first; arguments untouched if present
  m.insert_or_assign("a", 10);     // always ends with a == 10
  int y = m.at("a");               // throws std::out_of_range if missing
  (void)x; (void)y;

  std::map<int, NoDefault> n;
  n.try_emplace(1, 7);             // OK: constructs from args
  // n[1];                         // ill-formed: needs NoDefault()
}
```

`operator[]` is the odd one: it returns a reference to the mapped value, inserting a value-initialized one if needed, so it requires a default-constructible mapped type and does not exist on a const map. `at` is the pure lookup that reports a missing key with an exception. `find` returns an iterator and `contains` (C++20) returns a `bool`; `count` returns the number of matches.

`insert` and `emplace` return a pair of an iterator and a `bool` and never overwrite. They differ in that `emplace` may allocate a node and construct the element before it checks for the key, so with an existing key it can still move out of your arguments, whereas `try_emplace` (C++17) checks first and leaves its arguments alone. `try_emplace` also takes the key separately from the mapped value's constructor arguments, which makes it the right tool when the mapped value is expensive or move-only. `insert_or_assign` (C++17) is the one that overwrites, and, unlike `operator[]`, does not need a default constructor.

## Multi containers and `equal_range`

`multiset` and `multimap` allow equivalent keys. They have no `operator[]` or `at`, since a key may map to several values, and `insert` always succeeds, returning just an iterator. The standard guarantees that a new element goes at the upper end of its equivalent range, so equivalent elements stay in insertion order. `erase(key)` removes all of them and returns the count; to remove one, erase by iterator. `equal_range(k)` is the way to visit them all, and for the unordered multi containers it returns a range whose elements are guaranteed to be adjacent in iteration order.

> **Standardese.** [associative.reqmts] requires `Compare` to induce a strict weak ordering and defines equivalence in terms of it. [unord.req] says that if the equality predicate holds for two keys, the hash function must return the same value for both. Violating either requirement is undefined behavior, not an error the compiler can detect.

## Choosing between them

Pick an ordered container when you need sorted iteration, range queries with `lower_bound` and `upper_bound`, a worst case you can state, or a key type that has an ordering but no good hash. Pick an unordered one when lookups dominate and the keys hash well. Both pay one heap allocation per element and chase pointers on every lookup. For small collections, or ones built once and read many times, a sorted `vector` or the C++23 flat containers often beat both, as the topic on container adaptors and flat containers explains.

Reserve unordered containers when you know the size, and watch for hash quality: a hash that maps all keys to a few values turns constant time into linear time without any compiler warning.

## What to remember

- Ordered containers are sorted trees: logarithmic operations, sorted iteration, keys compared only with the comparator, which must be a strict weak ordering.
- Unordered containers are hash tables: constant on average and linear in the worst case, unspecified iteration order.
- Keys are const inside the container, because changing one would break the structure.
- A rehash invalidates iterators but not references or pointers to elements; `reserve(n)` avoids rehashing up to `n` elements.
- Equal keys must have equal hashes, and `std::hash` must be specialized or replaced for your own key types.
- `operator[]` inserts; `at` throws; `insert` and `emplace` never overwrite; `try_emplace` does not touch its arguments for an existing key; `insert_or_assign` overwrites.
- `contains` (C++20) is the clear way to test membership.
- Multi containers keep equivalent elements in insertion order, and `erase(key)` removes all of them.

## Concept Map Outline

- **Associative and unordered:** Sorted trees driven by a comparator versus hash tables driven by hash and equality.
  - **Ordered containers:** set, map and multi versions are sorted, node based and logarithmic.
    - **Strict weak ordering:** Compare must make comp(x, x) false; a violation such as less_equal is undefined behavior.
    - **Equivalence not equality:** Two keys are the same key when neither compares less than the other.
    - **Range queries:** lower_bound, upper_bound and equal_range exploit the sort order.
  - **Unordered containers:** Hash tables: constant average cost, linear worst case, unspecified order.
    - **Buckets and load factor:** Load factor is size over bucket count; max_load_factor defaults to 1.0.
    - **Rehash:** Growing the bucket count redistributes elements and invalidates iterators, not references.
    - **reserve(n):** Equals rehash(ceil(n / max_load_factor())); it avoids rehashing up to n elements.
  - **Keys and hashing:** Rules the container cannot check for you.
    - **Const keys:** The element type is pair<const K, V>, because changing a key would break the structure.
    - **Equal keys, equal hashes:** If the equality predicate holds, the hashes must match, or behavior is undefined.
    - **Specializing std::hash:** Allowed for your own types; std::hash has no pair or tuple specialization.
  - **Insertion functions:** They differ in overwrite behavior and in when they construct.
    - **operator[]:** Inserts a value-initialized element if missing; needs a default constructor; absent on const maps.
    - **at and find:** at throws std::out_of_range for a missing key; find returns end and changes nothing.
    - **insert and emplace:** Never overwrite; emplace may build a node before discovering the key exists.
    - **try_emplace:** C++17: leaves its arguments untouched when the key already exists.
    - **insert_or_assign:** C++17: always ends with the new value and needs no default constructor.
  - **Multi containers:** Equivalent keys are allowed.
    - **Insertion order kept:** A new element goes at the upper end of its equivalent range.
    - **erase(key):** Removes every equivalent element and returns the count; erase by iterator removes one.
    - **No operator[] or at:** A key may map to several values, so key-based access is not offered.
  - **Stability and choice:** Node storage gives stable addresses; choose by needs.
    - **Stable addresses:** Elements never move while in the container, so references and pointers survive insertion.
    - **contains:** C++20 membership test returning bool on all eight containers.

## Standardese Quiz Questions

### Question 1 [warmup] ([map.access], [associative.reqmts])

What does this program print?

```cpp
#include <iostream>
#include <map>

int main() {
  std::map<int, int> m;
  int a = m[5];
  std::cout << m.size() << ' ' << a << '\n';
}
```

A. 0 0
B. 1 0
C. Throws `std::out_of_range`
D. Undefined behavior: there is no key 5

**Answer (B):** 1 0

**Why:** `operator[]` on a map inserts a value-initialized element when the key is missing, then returns a reference to it. So the size becomes 1 and `a` is 0. Reading with `[]` is therefore never a pure lookup; `at` is the lookup that throws `std::out_of_range`, and `find` or `contains` do not modify anything.

### Question 2 [warmup] ([associative.reqmts])

What does this program print?

```cpp
#include <iostream>
#include <map>

int main() {
  std::map<int, int> m;
  m.insert({1, 10});
  auto [it, inserted] = m.insert({1, 20});
  std::cout << it->second << ' ' << inserted << '\n';
}
```

A. 20 1
B. 20 0
C. 10 1
D. 10 0

**Answer (D):** 10 0

**Why:** `insert` never overwrites. When an equivalent key is present it does nothing and returns an iterator to the existing element together with `false`, so the mapped value is still 10 and `inserted` prints as 0. To replace a value use `insert_or_assign` or assign through `operator[]`.

### Question 3 [warmup] ([map.overview], [associative.reqmts])

Is this program well-formed?

```cpp
#include <map>
#include <string>

int main() {
  std::map<std::string, int> m{{"a", 1}};
  auto it = m.begin();
  it->first = "b";
}
```

A. Yes; the node is re-keyed and the map stays ordered
B. Yes, but the behavior is undefined because the order may break
C. No: the key member of the element is `const`
D. Yes; the map re-sorts itself on the next lookup

**Answer (C):** No: the key member of the element is `const`

**Why:** The element type of `map<K, V>` is `pair<const K, V>`, so assigning to `it->first` is rejected at compile time. The constness is what protects the container's ordering invariant. To change a key you must erase the element and insert a new one, or move the node out with `extract` and change `key()` on the node handle.

### Question 4 [tricky] ([map.modifiers])

What is guaranteed to be printed?

```cpp
#include <iostream>
#include <map>
#include <string>
#include <utility>

int main() {
  std::map<int, std::string> m;
  m.emplace(1, "old");
  std::string s(30, 'x');
  m.try_emplace(1, std::move(s));
  std::cout << s.size() << ' ' << m[1] << '\n';
}
```

A. 0 old
B. Unspecified: `s` may or may not have been moved from
C. 30 old
D. 0 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

**Answer (C):** 30 old

**Why:** `try_emplace` looks the key up first and, if it exists, does nothing: the arguments are not moved from. So `s` still holds its 30 characters and the old value stays. With `emplace`, the standard allows the node to be built before the key check, so the same call would leave `s` unspecified, which is why the second option is tempting.

### Question 5 [tricky] ([associative.reqmts])

What does this program print?

```cpp
#include <iostream>
#include <set>

int main() {
  std::multiset<int> s{1, 1, 1, 2};
  auto n = s.erase(1);
  std::cout << n << ' ' << s.size() << '\n';
}
```

A. 3 1
B. 1 3
C. 1 1
D. Ill-formed: `erase(key)` is not available on a multiset

**Answer (A):** 3 1

**Why:** `erase(const key_type&)` removes every element whose key is equivalent and returns how many it removed, three here, leaving only the 2. To erase a single one of several equivalent elements you must erase by iterator, for example `s.erase(s.find(1))`.

### Question 6 [tricky] ([associative.reqmts])

In what order are the mapped values printed?

```cpp
#include <iostream>
#include <map>

int main() {
  std::multimap<int, char> m;
  m.insert({1, 'a'});
  m.insert({1, 'b'});
  m.insert({0, 'z'});
  m.insert({1, 'c'});
  for (auto [k, v] : m) std::cout << v;
  std::cout << '\n';
}
```

A. zcba
B. zabc
C. Unspecified: equivalent keys may appear in any order
D. abzc

**Answer (B):** zabc

**Why:** Elements are ordered by key, and `insert` on a multimap places a new element at the upper end of its equivalent range, so equivalent elements keep insertion order. The 0 comes first, then a, b, c. The fourth option is plain insertion order, which ignores the key ordering; the third is wrong because this guarantee exists for `insert` and `emplace`.

### Question 7 [standardese] ([unord.req])

What does the standard say about this program?

```cpp
#include <cstddef>
#include <unordered_set>

struct Hash {
  std::size_t operator()(int x) const { return static_cast<std::size_t>(x); }
};
struct Eq {
  bool operator()(int a, int b) const { return a % 10 == b % 10; }
};

int main() {
  std::unordered_set<int, Hash, Eq> s;
  s.insert(1);
  s.insert(11);
}
```

A. Ill-formed: the hash and equality types must agree
B. The set ends with one element
C. The set ends with two elements
D. Undefined behavior: keys that compare equal must hash equally

**Answer (D):** Undefined behavior: keys that compare equal must hash equally

**Why:** The requirements on an unordered container say that if `Pred(a, b)` is true, then `Hash(a) == Hash(b)` must hold. Here 1 and 11 compare equal but hash to different values, which violates a library requirement and makes the behavior undefined. Observing one or two elements on a given implementation proves nothing; the compiler cannot diagnose the mismatch.

### Question 8 [standardese] ([associative.reqmts], [alg.sorting])

What does the standard say about this program?

```cpp
#include <functional>
#include <set>

int main() {
  std::set<int, std::less_equal<int>> s;
  s.insert(1);
  s.insert(1);
}
```

A. Undefined behavior: `Compare` must be a strict weak ordering
B. Ill-formed: `std::less_equal` is not a valid `Compare`
C. The set holds one element
D. The set holds two elements

**Answer (A):** Undefined behavior: `Compare` must be a strict weak ordering

**Why:** `Compare` for an ordered container must induce a strict weak ordering, which requires `comp(x, x)` to be false. `less_equal` returns true for equal arguments, so the requirement is violated and the behavior is undefined. It compiles, and many implementations will store two elements, but that is an accident of the tree code rather than a guarantee.

# Iterator invalidation

> An iterator is a handle into a container's storage, and an operation invalidates it exactly when that storage or the machinery for finding it changes. Learn each container's layout and the invalidation rules can be derived rather than memorized.

- **Source:** C++ Atlas (https://cppatlas.com/topics/iterator-invalidation)
- **Track:** Containers and strings
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [container.reqmts] (https://eel.is/c++draft/container.reqmts), [vector.modifiers] (https://eel.is/c++draft/vector.modifiers), [vector.capacity] (https://eel.is/c++draft/vector.capacity), [deque.modifiers] (https://eel.is/c++draft/deque.modifiers), [list.modifiers] (https://eel.is/c++draft/list.modifiers), [associative.reqmts] (https://eel.is/c++draft/associative.reqmts), [unord.req] (https://eel.is/c++draft/unord.req), [string.require] (https://eel.is/c++draft/string.require)
- **cppreference links:** [Iterator invalidation rules for C++ containers](https://en.cppreference.com/w/cpp/container), [std::vector::erase](https://en.cppreference.com/w/cpp/container/vector/erase), [std::deque::insert](https://en.cppreference.com/w/cpp/container/deque/insert), [std::unordered_map::rehash](https://en.cppreference.com/w/cpp/container/unordered_map/rehash), [std::erase_if (std::map)](https://en.cppreference.com/w/cpp/container/map/erase_if)
- **Prerequisites:** sequence-containers, associative-and-unordered-containers

## The one idea

An iterator, a pointer and a reference to an element are three ways of naming an element, and they break for different reasons. A pointer or reference breaks when the element moves or dies. An iterator breaks in those cases too, and also when the **navigation machinery** it depends on changes: the block index of a `deque`, the bucket array of a hash table, the end of a `vector`.

So there is no table to memorize. For each container ask three questions of an operation. Did any element move in memory? Did an element die? Did the structure used to reach elements change?

> **Mental model.** Invalidation is a statement about storage, not about the operation's name. If an operation leaves every element where it is, only iterators tied to a changed structure break. If it moves elements, all names for them break.

Once invalidated, an iterator is in a singular state. The only things you may do with it are assign to it or destroy it. Dereferencing, incrementing and comparing it are all undefined behavior, even when the memory it points at looks fine.

## `vector`: contiguous storage

A `vector` has two events. **Reallocation** moves every element into a new block, so all iterators, pointers, references, and the end iterator die. This happens when the new size would exceed `capacity()`. Without reallocation, elements before the point of change stay put.

- Insertion without reallocation invalidates iterators and references at or after the insertion point, and the end iterator. Those before the point stay valid.
- Insertion that reallocates invalidates everything.
- Erasure invalidates iterators and references at or after the erased position, including the end iterator, because later elements shift down.
- `reserve` and `shrink_to_fit` invalidate everything if they reallocate, and nothing otherwise. `clear` and `assign` invalidate everything.

After `v.reserve(n)`, the standard guarantees no reallocation until the size would exceed `capacity()`, so iterators to existing elements survive appends up to that limit.

```cpp
#include <vector>

void demo() {
  std::vector<int> v{1, 2, 3};
  v.reserve(100);
  auto it = v.begin();
  v.push_back(4);   // no reallocation: it is still valid, v.end() is not
  *it = 0;          // OK

  auto e = v.end();
  v.push_back(5);
  // e is invalidated even if there was no reallocation
  (void)e;
}
```

Erasure and the saved `end()` cause the most bugs. `end()` is the one iterator that every erase and every insertion invalidates, so a loop that caches it is wrong the moment the loop body changes the vector.

## `deque`: the asymmetric one

A `deque` stores elements in fixed-size blocks and finds them through an index of blocks. Adding an element at either end may allocate a new block and grow that index, and iterators are tied to the index, so all iterators die. Elements themselves are never moved by an end insertion, so pointers and references survive.

- Insertion at the front or back invalidates all iterators, including `end()`, but no references or pointers.
- Insertion in the middle shifts elements, so it invalidates all iterators and references.
- Erasing the last element invalidates only the erased element's iterators and references, plus the end iterator.
- Erasing the first element, if it is not also the last, invalidates only that element's iterators and references.
- Erasing from the middle invalidates everything, including the end iterator.

```cpp
#include <deque>

void demo() {
  std::deque<int> d{1, 2, 3, 4};
  auto it = d.begin() + 2;     // refers to 3
  int& r = d[3];               // refers to 4
  d.erase(d.begin());          // erasing the first element: it and r stay valid
  d.push_back(5);              // it is invalid now; r is still valid
  r = 0;                       // OK
}
```

The erase-at-front rule surprises people who know that `vector` and `deque` look alike. Nothing shifts, because the front is simply abandoned.

## Node containers: `list`, `forward_list`, `map`, `set` and friends

Every element has its own node, and nodes never move. So insertion invalidates nothing, and erasure invalidates only iterators and references to the erased elements. This is the whole rule for `list`, `forward_list`, `set`, `map` and their multi versions.

Two details are worth knowing. The `end()` iterator of these containers stays valid under erase, since it does not name an element. And `list::splice` keeps iterators valid, with the caveat that they now belong to the destination list.

## Unordered containers

The nodes are stable, but iterators can walk across buckets, and the bucket array can be rebuilt. The rules are:

- Insertion that does not trigger a rehash invalidates nothing.
- Insertion that triggers a rehash invalidates all iterators, but not pointers or references to elements.
- `rehash` and `reserve` invalidate all iterators and no references.
- Erasure invalidates only the erased elements.

```cpp
#include <unordered_map>

void demo() {
  std::unordered_map<int, int> m{{1, 10}};
  auto it = m.find(1);
  int& r = it->second;
  m.reserve(1000);          // may rehash
  r = 20;                   // OK: references survive
  // *it = ...;             // undefined behavior: iterators do not
}
```

> **Pitfall.** Inserting into an unordered container while iterating over it is only safe if you know no rehash can occur. With `m.reserve` large enough up front it cannot, but without it, an insertion in a loop body can invalidate the loop's own iterator.

## `string`, swap, move and `end()`

`std::string` follows the conservative rule that nearly any non-const member call may invalidate iterators, pointers and references. The exceptions are `operator[]`, `at`, `data`, `front`, `back` and the iterator getters. One reason is the small-string optimization: short strings live inside the object, so even a swap or a move can relocate characters. Treat any mutation of a string as invalidating everything. The topic on strings covers the rest.

For the other containers, `swap` invalidates nothing. Iterators, pointers and references keep referring to the same elements, which now belong to the other container. `std::array` is the exception: its swap exchanges element values, so iterators stay associated with their original array and now see the swapped values.

```cpp
#include <vector>

void demo() {
  std::vector<int> a{1, 2, 3}, b{4, 5};
  auto it = a.begin();
  a.swap(b);
  // it still refers to the element 1, which is now b[0]
  // it == b.begin() is true; *it is 1
  (void)it;
}
```

The same logic covers moving. For all containers except `array`, move construction and move assignment with an allocator that propagates (always true for `std::allocator`) leave references, pointers and iterators into the source valid, and they refer to the elements now in the destination. This is what makes `std::vector` moves constant time. The moved-from container itself is valid but unspecified, and the `end()` iterator is never covered by these guarantees.

> **Standardese.** [container.reqmts] states that, unless otherwise specified, `swap` does not invalidate iterators, references or pointers into the swapped containers, and that move construction does not invalidate them for any container except `array`. In both cases a note adds that `end()` names no element and may be invalidated.

## Erasing while iterating

The rule for every erasing loop is the same: use the iterator the erase function returns, because the old one is dead. `erase` returns an iterator to the element after the last one removed, so the loop can carry on from there.

```cpp
#include <list>
#include <map>
#include <vector>

void demo() {
  std::vector<int> v{1, 2, 3, 4, 5, 6};
  for (auto it = v.begin(); it != v.end();) {
    if (*it % 2 == 0) it = v.erase(it);   // returns the next valid position
    else ++it;
  }

  std::map<int, int> m{{1, 1}, {2, 2}, {3, 3}, {4, 4}};
  for (auto it = m.begin(); it != m.end();) {
    if (it->first % 2 == 0) it = m.erase(it);  // C++11: erase returns the next
    else ++it;
  }

  std::list<int> l{1, 2, 3, 4};
  for (auto it = l.begin(); it != l.end();) {
    if (*it % 2 == 0) l.erase(it++);   // OK only for node containers
    else ++it;
  }
}
```

The `erase(it++)` form works because the increment happens before the call and node containers invalidate only the erased element. It would be undefined behavior for a `vector`.

Better still, do not write the loop. C++20 added `std::erase_if(container, pred)` for the sequence containers and for every associative and unordered container, and it returns the number of elements removed. For `vector` it is the erase-remove idiom in one call. The loop above that is needed only when the body needs to do more than remove.

## Why use after invalidation is undefined behavior

The standard says an invalidated iterator is singular and may only be assigned to or destroyed. The reason is practical: an iterator in most containers is a pointer or a pointer plus bookkeeping, and checking validity on every dereference would add a cost the standard does not mandate. After a reallocation, the old pointer addresses freed memory. After a rehash, the old iterator points into a bucket array that no longer exists.

That something "worked in testing" is therefore not evidence. A debug mode can catch it: libstdc++ built with `_GLIBCXX_DEBUG` aborts with a message about a singular iterator, and MSVC's iterator debugging does something similar. These are tools to find the bug, not a promise that the program is defined without them.

## What to remember

- Ask three questions: did elements move, did an element die, did the structure for finding elements change?
- `vector`: reallocation kills everything; otherwise only iterators and references at or after the change, and `end()`.
- `deque`: end insertion kills iterators but not references; erasing the first or last element is gentle; the middle kills everything.
- Node containers: insertion invalidates nothing; erase invalidates only the erased elements.
- Unordered containers: a rehash kills iterators but not references or pointers.
- `string` is conservative; `swap` and move keep iterators valid and moved to the other container, except `array`.
- `end()` is not an element, so most guarantees do not cover it. Do not cache it across modifications.
- In erase loops use the iterator that `erase` returns, or call `std::erase_if`.
- Using an invalidated iterator is undefined behavior even if it appears to work.

## Concept Map Outline

- **Iterator invalidation:** An iterator dies when storage or navigation structure changes; derive the rules from the layout.
  - **Three questions:** Ask: did elements move, did one die, did the structure used to find elements change.
    - **Singular state:** An invalidated iterator may only be assigned to or destroyed; any other use is undefined.
    - **Iterators vs references:** Iterators also depend on index structures, so they can die while references survive.
  - **vector:** Contiguous storage: reallocation moves everything, shifting moves the tail.
    - **Reallocation:** When size would exceed capacity, all iterators, pointers, references and end() are invalidated.
    - **No reallocation:** Insert or erase invalidates iterators and references at or after the change, plus end().
    - **reserve guarantee:** After reserve(n), appends up to capacity do not reallocate, so earlier iterators survive.
  - **deque:** Blocks plus an index: asymmetric rules for iterators and references.
    - **End insertion:** Push at either end invalidates all iterators including end(), but no references or pointers.
    - **Erase at an end:** Erasing the first (not last) element hits only that element; erasing the last also kills end().
    - **Middle edit:** Any insertion or erasure in the middle invalidates all iterators and references.
  - **Node containers:** list, forward_list, set, map and multi versions never move elements.
    - **Insert:** Insertion invalidates nothing.
    - **Erase:** Only iterators and references to the erased elements are invalidated; end() survives.
    - **splice:** Iterators remain valid but now belong to the destination list.
  - **Unordered containers:** Stable nodes, rebuildable bucket array.
    - **Rehash:** A rehash invalidates all iterators but not pointers or references to elements.
    - **No rehash:** Insertion without rehash invalidates nothing; erase affects only erased elements.
  - **Special cases:** Swap, move, string and end() need separate care.
    - **swap and move:** Iterators stay valid and refer into the other container; array swap exchanges values instead.
    - **string:** Conservative: almost any non-const member may invalidate; operator[], at, data and iterator getters do not.
    - **Erase loops:** Use it = c.erase(it) or std::erase_if; never reuse the erased iterator.

## Standardese Quiz Questions

### Question 1 [warmup] ([vector.capacity], [vector.modifiers])

What does the standard say about this program?

```cpp
#include <iostream>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3};
  v.reserve(100);
  auto it = v.begin();
  v.push_back(4);
  std::cout << *it << '\n';
}
```

A. It prints 1
B. Undefined behavior: `push_back` invalidates all iterators
C. It prints 4
D. Implementation-defined

**Answer (A):** It prints 1

**Why:** After `reserve(100)`, no reallocation takes place until the size would exceed the capacity. Appending a fourth element therefore leaves every iterator before the insertion point valid, so `it` still refers to the element 1. Only `end()` is invalidated. The second option would be right if `push_back` had to reallocate.

### Question 2 [warmup] ([list.modifiers], [container.reqmts])

What does this program print?

```cpp
#include <iostream>
#include <iterator>
#include <list>

int main() {
  std::list<int> l{1, 2, 3};
  auto a = l.begin();
  auto b = std::next(a);
  auto c = std::next(b);
  l.erase(b);
  std::cout << *a << ' ' << *c << '\n';
}
```

A. Undefined behavior: `erase` invalidates every iterator
B. Undefined behavior: `erase` invalidates iterators after the erased element
C. 1 3

**Answer (C):** 1 3

**Why:** `list` has one node per element and erasing one node touches only its neighbours' links. Only iterators and references to the erased element are invalidated, so `a` and `c` are still valid and the output is `1 3`. The other options describe `vector::erase`, where elements after the erase point shift.

### Question 3 [warmup] ([vector.modifiers], [stmt.ranged])

What does the standard say about this program?

```cpp
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3};
  for (int x : v)
    if (x == 2) v.push_back(4);
}
```

A. It visits 1, 2, 3 and then 4
B. Undefined behavior: the loop's cached `end()` iterator is invalidated
C. It visits 1, 2, 3 and stops, because the range was fixed on entry
D. Ill-formed: a container cannot be modified inside a range-for

**Answer (B):** Undefined behavior: the loop's cached `end()` iterator is invalidated

**Why:** A range-for evaluates `begin()` and `end()` once, then keeps using those iterators. `push_back` invalidates `end()` even when it does not reallocate, and invalidates every iterator when it does, so the loop increments and compares invalidated iterators. The third option is the intuition the standard does not back, and the fourth is wrong because the code compiles.

### Question 4 [tricky] ([deque.modifiers])

What does the standard guarantee this program prints?

```cpp
#include <deque>
#include <iostream>

int main() {
  std::deque<int> d{1, 2, 3, 4};
  auto it = d.begin() + 2;  // refers to 3
  d.erase(d.begin());
  std::cout << *it << '\n';
}
```

A. 4
B. Unspecified
C. Undefined behavior: erase invalidates all deque iterators
D. 3

**Answer (D):** 3

**Why:** Erasing the first element of a `deque` (but not the last) invalidates only iterators and references to the erased element, because the other elements do not move. `it` still refers to the element 3. The third option is the rule for erasing in the middle, where every iterator is invalidated; the first imagines elements shifting down as in a `vector`.

### Question 5 [tricky] ([unord.req], [container.reqmts])

Which of the two uses after `reserve` is valid?

```cpp
#include <iostream>
#include <unordered_map>

int main() {
  std::unordered_map<int, int> m{{1, 10}};
  auto it = m.find(1);
  int& r = it->second;
  m.reserve(1000);
  std::cout << r << '\n';          // use A
  std::cout << it->second << '\n'; // use B
}
```

A. Both
B. Only A
C. Only B
D. Neither

**Answer (B):** Only A

**Why:** `reserve` may rehash, and a rehash invalidates all iterators but not pointers or references to elements, because the elements live in nodes that are not moved. Use A is valid and use B is undefined behavior. The tempting answer "Both" assumes that if the element survives, the iterator does too.

### Question 6 [tricky] ([container.reqmts])

What does the standard guarantee this program prints?

```cpp
#include <iostream>
#include <vector>

int main() {
  std::vector<int> a{1, 2, 3}, b{4, 5};
  auto it = a.begin();
  a.swap(b);
  std::cout << *it << ' ' << (it == b.begin()) << '\n';
}
```

A. 4 0
B. 1 0
C. 1 1
D. Undefined behavior: swap invalidates iterators

**Answer (C):** 1 1

**Why:** Unless a container says otherwise, `swap` invalidates no references, pointers or iterators to elements; they keep referring to the same elements, which now belong to the other container. So `it` still names the element 1, which is now the first element of `b`, and the comparison is true. `std::array` is the exception, since its swap exchanges elements.

### Question 7 [standardese] ([vector.modifiers])

After the erase, which of the iterators `a` and `c` may the program still use?

```cpp
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3, 4};
  [[maybe_unused]] auto a = v.begin();
  auto b = a + 1;
  [[maybe_unused]] auto c = a + 2;
  v.erase(b);
}
```

A. Only `a`
B. Both `a` and `c`
C. Only `c`
D. Neither

**Answer (A):** Only `a`

**Why:** `vector::erase` invalidates iterators and references at or after the point of the erase. `a` precedes it and stays valid; `c` is after it, so using `c` is undefined behavior even though, on typical implementations, it would point at the element 4. The shifted element is what makes "Both" tempting.

### Question 8 [standardese] ([container.reqmts])

What does the standard guarantee this program prints?

```cpp
#include <iostream>
#include <utility>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3};
  int* p = v.data();
  std::vector<int> w = std::move(v);
  std::cout << *p << ' ' << (p == w.data()) << '\n';
}
```

A. Undefined behavior: the moved-from vector released its storage
B. 1 0, because the elements were copied
C. 1 1
D. Unspecified

**Answer (C):** 1 1

**Why:** The container requirements say that, apart from `array`, no move constructor invalidates references, pointers or iterators (other than `end()`) into the source. They keep referring to the same elements, which now belong to `w`. So `p` is valid and equals `w.data()`. The moved-from `v` itself is left in a valid but unspecified state, which is a separate matter from its former elements.

# Container adaptors and flat containers

> stack, queue and priority_queue restrict a real container to a narrow interface, and the C++23 flat_map and flat_set family turns sorted vectors into associative containers. Both trade a wide interface for a layout you can reason about, and both have sharp edges.

- **Source:** C++ Atlas (https://cppatlas.com/topics/container-adaptors-and-flat-containers)
- **Track:** Containers and strings
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [container.adaptors] (https://eel.is/c++draft/container.adaptors), [stack] (https://eel.is/c++draft/stack), [queue] (https://eel.is/c++draft/queue), [priority.queue] (https://eel.is/c++draft/priority.queue), [flat.map] (https://eel.is/c++draft/flat.map), [flat.set] (https://eel.is/c++draft/flat.set)
- **cppreference links:** [std::stack](https://en.cppreference.com/w/cpp/container/stack), [std::queue](https://en.cppreference.com/w/cpp/container/queue), [std::priority_queue](https://en.cppreference.com/w/cpp/container/priority_queue), [std::flat_map](https://en.cppreference.com/w/cpp/container/flat_map), [std::flat_set](https://en.cppreference.com/w/cpp/container/flat_set), [std::sorted_unique](https://en.cppreference.com/w/cpp/container/sorted_unique), [std::flat_map::extract](https://en.cppreference.com/w/cpp/container/flat_map/extract)
- **Prerequisites:** sequence-containers, associative-and-unordered-containers, iterator-invalidation

## The one idea

A container adaptor is not a container. It holds a real container, the **underlying container**, as a data member and exposes only a few operations on it. `stack` shows the back, `queue` shows both ends, and `priority_queue` keeps a heap inside a random access container and shows only the largest element. The restriction is the feature: it states what the program needs and prevents anything else.

The C++23 flat containers use the same trick in the other direction. `flat_map` and `flat_set` hold a sorted sequence container, or two for a map, and add associative operations on top. They are adaptors that give you the interface of `map` and `set` with the layout of a sorted `vector`.

> **Mental model.** An adaptor is a wrapper around a sequence container plus an invariant it maintains for you. A stack's invariant is "only the back is touched", a priority queue's is "the underlying range is a heap", and a flat map's is "keys are sorted and unique and values line up with them".

## `stack`, `queue` and `priority_queue`

The defaults are `deque` for `stack` and `queue`, and `vector` for `priority_queue`. You may substitute any container that supplies the operations the adaptor calls. A stack needs `back`, `push_back` and `pop_back`. A queue needs `front`, `back`, `push_back` and `pop_front`, so it works over `deque` and `list` but not `vector`. A priority queue needs random access iterators, plus `front`, `push_back` and `pop_back`.

The requirements are checked lazily. A `std::queue<int, std::vector<int>>` can be declared and pushed to, and fails to compile only when you call `pop()`, which needs `pop_front`.

```cpp
#include <list>
#include <queue>
#include <stack>
#include <vector>

std::stack<int, std::vector<int>> s;   // a vector-backed stack: common and fast
std::queue<int, std::list<int>> q;     // OK: list has pop_front
// std::queue<int, std::vector<int>> bad; bad.pop();   // ill-formed: no pop_front
```

The interface is deliberately small. There are no iterators, so you cannot walk a stack, a queue or a priority queue; popping is the only way to see an element other than the top. `pop()` returns `void`, and `top()` and `front()` return references. A `pop` that returned the element by value could lose it if the copy or move out of the container threw, so the standard splits reading from removing. Calling `top`, `front` or `pop` on an empty adaptor is undefined behavior.

## `priority_queue`: comparator direction and the const top

`priority_queue<T, Container, Compare>` keeps the elements of its container arranged as a heap using `push_heap` and `pop_heap`. `push` and `pop` are logarithmic, `top` is constant, and building from a range is linear.

The comparator is where people trip. `Compare(a, b)` returns true when `a` comes before `b` in a weak ordering, and the queue's top is the element that comes last. The default `std::less` therefore produces a max-heap, and `std::greater` a min-heap. The comparator expresses "is lower priority than", not "should be served first".

```cpp
#include <functional>
#include <queue>
#include <vector>

std::priority_queue<int> maxq;                                         // top is largest
std::priority_queue<int, std::vector<int>, std::greater<int>> minq;   // top is smallest
```

`top()` returns a `const` reference, because changing the top element in place would silently break the heap. That has a consequence for move-only or expensive elements: `std::move(pq.top())` is a `const T&&`, which binds to the copy constructor, so you copy and leave the original in the queue.

> **Pitfall.** `T x = std::move(pq.top()); pq.pop();` compiles and runs, but it copies every time. The compiler may warn about the redundant move, which is a hint that it does nothing.

There is no member that extracts an element, but the underlying container and comparator are `protected` members named `c` and `comp`, and the standard specifies that, so a derived class can pop the heap properly and move the element out.

```cpp
#include <algorithm>
#include <functional>
#include <queue>
#include <utility>
#include <vector>

template <class T, class C = std::vector<T>, class Cmp = std::less<T>>
struct MovablePQ : std::priority_queue<T, C, Cmp> {
  T pop_value() {
    std::pop_heap(this->c.begin(), this->c.end(), this->comp);  // top moves to the back
    T v = std::move(this->c.back());
    this->c.pop_back();
    return v;
  }
};
```

C++23 adds range constructors that take `std::from_range`, and `push_range` members, to all three adaptors.

## Flat containers: sorted vectors with a map interface

C++23 added `flat_map`, `flat_set`, `flat_multimap` and `flat_multiset`. A `flat_set<T>` is a sorted `vector<T>` with no duplicates. A `flat_map<K, V>` is two vectors: a sorted vector of keys, and a vector of values where position `i` belongs to key `i`. The container types are template parameters, so you may use `deque` or any other random access container instead of `vector`.

```text
flat_map<int,char>:   keys   [ 1   3   7   9 ]   sorted, unique
                      values [ a   b   c   d ]   same positions
```

The trade-offs follow from that layout. Lookup is a binary search over contiguous memory, so it is logarithmic and cache friendly. Iteration is a linear scan and is very fast. Insertion and erasure in the middle shift elements of both vectors, so they are linear in the size. That is the opposite of `std::map`, where every operation is logarithmic and every access chases a pointer. A flat container wins when it is built once and read often, when it is small, or when iteration dominates; it loses on large containers with frequent random insertion.

Because the storage is a plain sequence, there are no nodes. That has three consequences. There are no node handles and no `merge`. Insertion and erasure invalidate iterators, references and pointers the way `vector` does, so treat every modification as invalidating everything; `clear` certainly does. And the memory is reusable: you can take the underlying containers out and put them back.

```cpp
#include <flat_map>
#include <utility>
#include <vector>

void demo() {
  std::flat_map<int, char> m{{3, 'c'}, {1, 'a'}};
  auto c = std::move(m).extract();       // m is now empty; c.keys == {1, 3}
  c.values[0] = 'z';                     // plain vectors, edit freely
  m.replace(std::move(c.keys), std::move(c.values));  // keys must be sorted, unique
}
```

`extract()` is rvalue-qualified and moves out both containers as a struct with `keys` and `values` members, leaving the map empty. `replace(keys, values)` installs them again, and the sizes must match, the keys must be sorted by the comparator, and they must be unique, or the behavior is undefined. `keys()` and `values()` give const access to the vectors without extracting.

## Building: `sorted_unique` and the cost of trust

Constructing from a general range sorts and removes duplicates. If you already have sorted, unique data, the tag `std::sorted_unique` says so and skips that work. The constructor believes you: if the data is not sorted or has equivalent keys, the behavior is undefined.

```cpp
#include <flat_map>
#include <flat_set>
#include <vector>

void demo() {
  std::vector<int> keys{1, 2, 3}, vals{10, 20, 30};
  std::flat_map<int, int> a(std::sorted_unique, keys, vals);   // trusted: O(n)
  std::flat_set<int> b{3, 1, 2, 3};                            // sorted, deduplicated
  // std::flat_set<int> c(std::sorted_unique, {3, 1, 2});      // undefined behavior
  (void)a; (void)b;
}
```

For bulk loading prefer `insert(first, last)` or `insert_range`, which append and merge, over a loop of single insertions that each shift the tail. For multi variants the tag is `std::sorted_equivalent`, which allows equal keys but still requires sorted order.

## The proxy-like reference of `flat_map`

A `flat_map` has no `pair<K, V>` objects in memory, so dereferencing an iterator cannot return a reference to one. Its `reference` type is `pair<const K&, V&>`, built on the fly and returned by value, while `value_type` is `pair<K, V>`. That differs from `map`, whose value type is `pair<const K, V>`, and it changes code that works with `map`.

```cpp
#include <flat_map>

void demo() {
  std::flat_map<int, int> m{{1, 10}, {2, 20}};
  // for (auto& [k, v] : m) v += 1;   // ill-formed: cannot bind auto& to a prvalue
  for (auto&& [k, v] : m) v += 1;     // OK
  for (auto [k, v] : m) v += 1;       // also modifies m: auto copies the pair of references
}
```

The last loop is the one that bites. `auto` copies the pair, but the pair holds references, so the value is still modified in the map. Write `auto&&`, or `const auto&` for read-only loops.

The same applies to code that stores `*it` in a variable or passes it to an algorithm expecting `value_type&`. The key is never mutable: the first element of the pair is `const K&`.

## Exception safety and implementation status

Two containers must stay in step. A flat map update is a pair of operations on two vectors, so the failure modes are different from a node-based `map`, where an insertion is a single allocation and either happens or does not. The reference documents a no-effect guarantee for single-element `insert` and `emplace`, and documents nothing for the range operations, so do not assume strong exception safety for bulk updates. The underlying containers' `size` and `max_size` must not throw.

For implementation status, I compiled and ran a `flat_map` and `flat_set` program with GCC 16.2 (libstdc++) and with Homebrew LLVM 21.1.2 (libc++), both on arm64 macOS, using `-std=c++23`. Both provide `<flat_map>` and `<flat_set>`, with the multi variants. GCC reports `__cpp_lib_flat_map` and `__cpp_lib_flat_set` as 202511, libc++ as 202207. In `-std=c++20` mode GCC does not provide the types. I did not check other implementations.

> **Standardese.** The synopses in [stack], [queue] and [priority.queue] declare the underlying container `c`, and for `priority_queue` also the comparator `comp`, as protected members, which is what makes a derived class legal and portable. For `flat_map` and `flat_set`, [flat.map] and [flat.set] define the `sorted_unique` overloads and say the input must be sorted and unique with respect to the comparator, so a violation is a precondition failure and therefore undefined behavior.

## What to remember

- An adaptor wraps a container and exposes a narrow interface; the underlying container is a template parameter.
- `stack` needs a back; `queue` needs `pop_front`, so not `vector`; `priority_queue` needs random access.
- Adaptors have no iterators, `pop()` returns `void`, and `top`, `front` and `pop` on an empty adaptor are undefined behavior.
- `priority_queue` surfaces the element that is last under the comparator: `less` gives a max-heap, `greater` a min-heap.
- `top()` is const so you cannot break the heap, which means `std::move(pq.top())` copies; move out through a derived class or `pop_heap` yourself.
- `flat_map` and `flat_set` are sorted vectors: logarithmic lookup, linear insertion and erasure, fast iteration.
- No nodes means no stable references and no node handles; `extract()` and `replace()` move whole containers in and out.
- `sorted_unique` skips sorting and trusts you; wrong input is undefined behavior.
- `flat_map` dereferences to `pair<const K&, V&>`: write `auto&&`, not `auto&`, and know that `auto` still writes through.
- GCC 16.2 and libc++ 21.1 both ship the flat containers in C++23 mode.

## Concept Map Outline

- **Adaptors and flat containers:** Narrow interfaces over real containers, and sorted vectors with a map interface.
  - **What an adaptor is:** It wraps an underlying container as a member and exposes a restricted interface.
    - **Underlying container:** A template parameter: deque for stack and queue, vector for priority_queue.
    - **Required operations:** queue needs pop_front, so vector fails at pop(); priority_queue needs random access.
    - **No iteration:** There are no iterators; pop() returns void, and top, front, pop on empty are undefined.
  - **priority_queue:** A heap kept in a random access container with push_heap and pop_heap.
    - **Comparator direction:** The top is the element that comes last: less gives a max-heap, greater a min-heap.
    - **Const top:** top() is const to protect the heap, so std::move(top()) copies instead of moving.
    - **Moving out:** Derive and use protected c and comp with pop_heap, then move from back().
    - **Complexity:** push and pop are logarithmic, top is constant, building from a range is linear.
  - **Flat container layout:** C++23 flat_map and flat_set wrap sorted sequence containers.
    - **Two vectors:** A flat_map keeps sorted keys and a parallel vector of values; flat_set keeps one sorted vector.
    - **Trade-offs:** Lookup is a cache-friendly binary search; insert and erase are linear; iteration is fast.
    - **No nodes:** No node handles or merge; insert and erase invalidate iterators and references like vector.
  - **Construction and access:** Bulk operations that trust the caller.
    - **sorted_unique:** Skips sorting; input that is unsorted or has duplicates is undefined behavior.
    - **extract and replace:** extract() moves out the keys and values containers; replace() needs equal sizes and sorted unique keys.
    - **sorted_equivalent:** The tag for multi variants: sorted input, equal keys allowed.
  - **flat_map reference type:** Dereferencing yields a prvalue pair of references.
    - **Pair of references:** reference is pair<const K&, V&> returned by value; value_type is pair<K, V>.
    - **auto& fails:** for (auto& [k, v] : m) is ill-formed; use auto&&, and know that auto still writes through.
  - **Status and safety:** Caveats for real-world use.
    - **Exception safety:** Two containers must stay in step; the reference documents no-effect only for single-element insertion.
    - **Implementation status:** GCC 16.2 libstdc++ and libc++ 21.1 ship the flat containers in C++23 mode.

## Standardese Quiz Questions

### Question 1 [warmup] ([priority.queue])

What does this program print?

```cpp
#include <iostream>
#include <queue>

int main() {
  std::priority_queue<int> pq;
  for (int x : {3, 1, 4, 1, 5}) pq.push(x);
  while (!pq.empty()) {
    std::cout << pq.top() << ' ';
    pq.pop();
  }
  std::cout << '\n';
}
```

A. 5 4 3 1 1
B. 1 1 3 4 5
C. 3 1 4 1 5
D. 5 4 3 1

**Answer (A):** 5 4 3 1 1

**Why:** The default comparator is `std::less`, and `priority_queue` surfaces the element that is largest under the comparator, so the default is a max-heap and the pops come out in descending order. Duplicates are kept, so the second 1 is printed too. Getting ascending order needs `std::greater` as the comparator.

### Question 2 [warmup] ([stack])

Is this program well-formed?

```cpp
#include <stack>

int main() {
  std::stack<int> s;
  s.push(1);
  int x = s.pop();
  (void)x;
}
```

A. No: `pop` returns `void`
B. Yes; `x` is 1
C. Yes; the value of `x` is unspecified
D. Yes, but undefined behavior at run time

**Answer (A):** No: `pop` returns `void`

**Why:** `stack::pop` only removes the top element and returns `void`. Reading is done with `top()` and removing with `pop()`, so the program is rejected at compile time. The split is deliberate: a `pop` that returned the element by value could lose it if the copy or move out threw.

### Question 3 [warmup] ([queue], [container.adaptors])

Is this program well-formed?

```cpp
#include <queue>
#include <vector>

int main() {
  std::queue<int, std::vector<int>> q;
  q.push(1);
  q.pop();
}
```

A. Yes
B. No: `queue` requires a `list` as its underlying container
C. No: `pop()` needs `pop_front`, which `vector` lacks
D. Yes, but `pop()` is undefined behavior for a `vector`

**Answer (C):** No: `pop()` needs `pop_front`, which `vector` lacks

**Why:** `queue` is built on the underlying container's `front`, `back`, `push_back` and `pop_front`. The class template can be named with a `vector`, and `push` works because `vector` has `push_back`, but `pop()` is implemented with `pop_front`, which `vector` does not provide. The default is `deque`; `list` also works.

### Question 4 [tricky] ([priority.queue])

What does this program print?

```cpp
#include <iostream>
#include <queue>
#include <vector>

int main() {
  auto cmp = [](int a, int b) { return a % 10 > b % 10; };
  std::priority_queue<int, std::vector<int>, decltype(cmp)> pq(cmp);
  for (int x : {15, 21, 7, 32}) pq.push(x);
  while (!pq.empty()) {
    std::cout << pq.top() << ' ';
    pq.pop();
  }
  std::cout << '\n';
}
```

A. 7 15 32 21
B. 21 32 15 7
C. 7 32 21 15
D. 32 21 15 7

**Answer (B):** 21 32 15 7

**Why:** The comparator returns true when its first argument should come before the second in the weak ordering, and the queue's top is the element that comes last in that ordering. With `>` on the last digit, larger last digits come first and the smallest last digit ends up on top: 1 (21), 2 (32), 5 (15), 7 (7). That is why `std::greater` gives a min-heap, and the opposite of the intuition "top is whatever my predicate prefers".

### Question 5 [tricky] ([priority.queue], [dcl.init.general])

What does this program print?

```cpp
#include <iostream>
#include <queue>
#include <string>
#include <utility>

int main() {
  std::priority_queue<std::string> pq;
  pq.push(std::string(30, 'x'));
  std::string s = std::move(pq.top());
  std::cout << s.size() << ' ' << pq.top().size() << '\n';
}
```

A. 30 0
B. Ill-formed: you cannot move from a const reference
C. Undefined behavior: the move breaks the heap
D. 30 30

**Answer (D):** 30 30

**Why:** `top()` returns a `const` reference, so `std::move(pq.top())` is a `const std::string&&`. That cannot bind to the move constructor, which takes a non-const rvalue reference, so overload resolution selects the copy constructor. The program is well-formed, `s` is a copy, and the queue's element is untouched. To really move an element out you need access to the underlying container, for example via a derived class with a `protected` member `c`, or by choosing a different design.

### Question 6 [tricky] ([flat.map])

In C++23, with a library that provides `<flat_map>`, is this program well-formed?

```cpp
#include <flat_map>

int main() {
  std::flat_map<int, int> m{{1, 10}, {2, 20}};
  for (auto& [k, v] : m) v += 1;
}
```

A. Yes; each value increases by one
B. Yes, but it increments copies, so `m` is unchanged
C. No: dereferencing an iterator yields a prvalue that `auto&` cannot bind to
D. Undefined behavior: keys must not be bound by reference

**Answer (C):** No: dereferencing an iterator yields a prvalue that `auto&` cannot bind to

**Why:** The keys and values live in two separate vectors, so there is no `pair<K, V>` in memory to refer to. `flat_map`'s `reference` type is a `pair<const K&, V&>` built on the fly, and `*it` returns it by value. A prvalue cannot bind to a non-const lvalue reference. `for (auto&& [k, v] : m)` works and modifies the values through the reference inside the pair.

### Question 7 [standardese] ([flat.set])

What does the standard say about this program?

```cpp
#include <flat_set>

int main() {
  std::flat_set<int> s(std::sorted_unique, {3, 1, 2});
}
```

A. It compiles and the set holds 1, 2, 3, sorted by the constructor
B. It is ill-formed: the tag cannot be used with a braced list
C. It throws `std::invalid_argument`
D. Undefined behavior: the elements must already be sorted and unique

**Answer (D):** Undefined behavior: the elements must already be sorted and unique

**Why:** The `sorted_unique` tag is a promise from the caller that the input is already sorted by the comparator and free of equivalent elements; the constructor trusts it and skips the sort. {3, 1, 2} is not sorted, so a precondition is violated and the behavior is undefined. Without the tag the constructor sorts and removes duplicates itself.

### Question 8 [standardese] ([flat.map])

What does the standard guarantee this program prints?

```cpp
#include <flat_map>
#include <iostream>
#include <utility>

int main() {
  std::flat_map<int, char> m{{2, 'b'}, {1, 'a'}};
  auto c = std::move(m).extract();
  std::cout << m.size() << ' ' << c.keys.size() << ' ' << c.keys[0] << '\n';
}
```

A. 2 2 1
B. 0 2 a
C. Ill-formed: `extract` takes a key, not nothing
D. 0 2 1

**Answer (D):** 0 2 1

**Why:** `flat_map::extract()` is rvalue-qualified; it moves the two underlying containers out into a `containers` struct with members `keys` and `values`, and leaves the flat_map empty even if an exception is thrown. The keys are sorted, so `keys[0]` is the integer 1, which prints as `1`; the character 'a' would be in `values[0]`. This is different from `std::map::extract(key)`, which returns a node handle.

# Strings, string_view, and span

> How std::string owns characters with Small String Optimization while std::string_view and std::span borrow contiguous memory safely without hidden allocations.

- **Source:** C++ Atlas (https://cppatlas.com/topics/strings-views-and-spans)
- **Track:** Containers and strings
- **Estimated reading time:** 10 minutes
- **ISO C++ clauses:** [basic.string] (https://eel.is/c++draft/basic.string), [string.require] (https://eel.is/c++draft/string.require), [string.view] (https://eel.is/c++draft/string.view), [string.view.cons] (https://eel.is/c++draft/string.view.cons), [views.span] (https://eel.is/c++draft/views.span)
- **cppreference links:** [std::basic_string](https://en.cppreference.com/w/cpp/string/basic_string), [std::basic_string_view](https://en.cppreference.com/w/cpp/string/basic_string_view), [std::span](https://en.cppreference.com/w/cpp/container/span), [std::as_bytes / std::as_writable_bytes](https://en.cppreference.com/w/cpp/container/span/as_bytes), [std::dynamic_extent](https://en.cppreference.com/w/cpp/container/span/dynamic_extent)
- **Prerequisites:** containers-and-iterator-invalidation, reference-binding-and-temporaries

Taking `const std::string&` as a function parameter used to be reflexive C++ advice, yet it silently couples every caller to heap-capable ownership. Passing a string literal `"GET /health"` or slicing three bytes out of a network packet through `const std::string&` forces construction of a temporary `std::string`, copying characters and potentially touching the allocator.

Modern C++ separates **storage ownership** from **contiguous borrowing**. `std::string` (`std::basic_string<char>`) owns its character buffer, whereas C++17 `std::string_view` and C++20 `std::span<T>` are lightweight, non-owning descriptors—essentially a pointer paired with a length—passed by value across API boundaries.

> **Mental model.** Ownership flows upward in return values (`std::string`, `std::vector<T>`); non-owning views flow downward in parameters (`std::string_view`, `std::span<const T>`). A view borrows memory it did not allocate and must never outlive the owner behind it.

## std::string, SSO, and the null-terminator invariant

Since C++11, `[string.require]` mandates that `std::basic_string` stores its elements contiguously in memory and maintains a trailing null terminator `CharT()` at `s[s.size()]`. Unlike pre-C++11 reference-counted copy-on-write strings—which were outlawed by C++11 thread-safety and invalidation rules—every modern `std::string` owns a unique buffer, and C++17 made `s.data()` return a mutable `CharT*` for non-`const` strings.

To avoid heap allocations for short strings, all major standard libraries implement the **Small String Optimization (SSO)**. When a string fits inside the object's inline byte budget (typically 15 characters on libstdc++ with `sizeof(std::string) == 32`, or 22 characters on libc++ with `sizeof(std::string) == 24`), the characters live inside the `std::string` object itself rather than on the heap:

```text
Short string (SSO active): [ inline char buffer[N] | inline size | flag ]  (no heap alloc)
Long string  (heap mode):  [ char* ptr | size | capacity        | flag ] ──▶ [ heap chars + '\0' ]
```

SSO makes short strings fast, but creates a subtle invalidation rule: **moving a `std::string` does not necessarily preserve pointers or views into its characters**. Moving a heap-mode string steals the heap pointer, whereas moving an SSO string must copy the inline bytes into the destination object and leave the source decoupled.

> **Pitfall.** Because moving an SSO `std::string` copies inline bytes into the new object's stack footprint, any `std::string_view`, pointer, or iterator pointing into the moved-from string becomes dangling or refers to the old buffer rather than the moved-to string.

When interfacing with C APIs that fill a caller-provided buffer, C++23 adds `resize_and_overwrite(max_cap, op)` so you can write directly into `std::string` storage without pre-zeroing unused bytes:

```cpp
#include <algorithm>
#include <cstring>
#include <string>

std::string build_greeting() {
    std::string out;
    out.resize_and_overwrite(64, [](char* buf, std::size_t cap) noexcept {
        constexpr char msg[] = "lucid-cpp";
        const std::size_t len = std::min(cap, sizeof(msg) - 1);
        std::memcpy(buf, msg, len);
        return len; // std::string writes buf[len] = '\0' automatically
    });
    return out;
}
```

## std::string_view: non-owning text without guarantees

`std::string_view` (`std::basic_string_view<char>`) consists solely of `{const char* data, std::size_t size}`. It is trivially copyable, two machine words wide, and converts implicitly from string literals, `const char*`, `std::string`, and (since C++20) contiguous sized character ranges. Because copying it copies two registers, pass `std::string_view` **by value**, never by `const std::string_view&`.

Two invariants separate `std::string_view` from `std::string`:

1. **No null-termination guarantee.** Slicing with `sv.remove_suffix(3)` or `sv.substr(2, 4)` simply adjusts `size_` or `data_` without copying bytes or inserting `'\0'`. Passing `sv.data()` directly to C functions expecting null-terminated strings (`std::fopen`, `std::printf("%s", ...)`, `std::strlen`) reads past the slice end and invokes undefined behavior.
2. **No lifetime ownership.** Binding `std::string_view` to a temporary `std::string` leaves the view dangling as soon as the temporary dies at the end of the full-expression. Returning a `std::string_view` from a function that constructs a local `std::string`, or storing `std::string_view` derived from a `const std::string&` parameter that a caller might satisfy with a temporary, creates immediate dangling references.

```cpp
#include <cstddef>
#include <string>
#include <string_view>

std::string_view trim_prefix(std::string_view sv, std::size_t n) {
    sv.remove_prefix(std::min(n, sv.size()));
    return sv; // Safe only while the caller's backing storage lives
}

void danger_examples() {
    // 1. Dangling: temporary std::string dies at the semicolon
    // std::string_view bad = std::string{"temp"} + "_key";

    // 2. Missing '\0' at sv.data()[sv.size()]
    std::string full = "header:body";
    std::string_view key{full.data(), 6}; // "header" — key.data()[6] is ':', not '\0'
    (void)key;
}
```

> **Standardese.** Prior to C++23, `std::string_view{nullptr}` selected the `const CharT*` constructor and caused immediate undefined behavior when computing string length. C++23 `[string.view.cons]` explicitly defines `basic_string_view(std::nullptr_t) = delete;`, turning null-pointer construction into a compile-time error.

## std::span: mutable or read-only views of contiguous memory

Where `std::string_view` models read-only character sequences, C++20 `std::span<T, Extent>` models a non-owning view over any contiguous sequence of `T` objects: `std::vector<T>`, `std::array<T, N>`, built-in arrays `T[N]`, or `(ptr, count)` pairs.

`std::span` provides two structural modes controlled by its second template parameter:

- **Dynamic extent (`std::span<T>`, default `Extent = std::dynamic_extent`):** stores `{T* ptr, std::size_t count}` (`sizeof == 2 * sizeof(void*)`) and accepts any contiguous range at runtime.
- **Static extent (`std::span<T, N>`):** encodes `N` in the type system, stores only `{T* ptr}` (`sizeof == sizeof(void*)`), and turns mismatched array sizes into compile-time diagnostics.

Crucially, **`const` on `std::span` is shallow**, matching pointer semantics rather than container semantics. `const std::span<int>` prevents rebinding the `span` to another array (`int* const`), while still allowing `s[0] = 42`. To promise read-only elements, put `const` inside the template argument: `std::span<const int>`.

```cpp
#include <array>
#include <cstddef>
#include <span>
#include <vector>

static_assert(sizeof(std::span<int, 4>) == sizeof(int*));
static_assert(sizeof(std::span<int>) == 2 * sizeof(int*));

int sum_first_two(std::span<const int> values) {
    auto head = values.first(values.size() >= 2 ? 2 : values.size());
    int total = 0;
    for (int v : head) {
        total += v;
    }
    return total;
}

void span_constness_and_bytes() {
    std::array<int, 4> arr{1, 2, 3, 4};
    const std::span<int> shallow_const{arr};
    shallow_const[0] = 99; // Well-formed: elements remain mutable

    std::span<const std::byte> raw = std::as_bytes(shallow_const);
    std::span<std::byte> rw_raw = std::as_writable_bytes(shallow_const);
    (void)raw;
    (void)rw_raw;
}
```

`std::as_bytes` and `std::as_writable_bytes` re-slice any span into `std::span<const std::byte>` or `std::span<std::byte>` (when `T` is non-`const`) with `size_bytes()` elements, giving serialization and hashing code a type-safe alternative to C-style `reinterpret_cast<const char*>` pointer arithmetic.

> **Pitfall.** Writing `const std::span<T>` as a function parameter does not prevent the function from mutating the caller's elements. Always write `std::span<const T>` for read-only array parameters.

## Choosing between string, string_view, and span

Selecting the right vocabulary type hinges on ownership, mutability, null-termination requirements, and lifetime scope.

| Type | Ownership | Null-terminated | Element mutability | Typical size | Primary role |
| --- | --- | --- | --- | --- | --- |
| `std::string` | Owning (unique or SSO) | Always (`s[size()] == '\0'`) | Mutable (unless `const`) | 24–32 bytes | Return values, stored fields, mutation |
| `std::string_view` | Non-owning | Not guaranteed | Read-only (`const char`) | 2 words | Read-only string parsing parameters |
| `std::span<const T>` | Non-owning | N/A | Read-only elements | 1 or 2 words | Read-only contiguous slice parameters |
| `std::span<T>` | Non-owning | N/A | Mutable elements | 1 or 2 words | In-place mutation of caller buffers |

Watch the **C++20 Ranges boundary** as well: both `std::string_view` and `std::span` satisfy `std::ranges::borrowed_range` and `std::ranges::view`, meaning algorithms can safely return iterators into rvalue `string_view` or `span` objects because their iterators point to underlying storage independent of the lightweight wrapper. `std::string` is neither a `view` nor a `borrowed_range`, so calling `std::ranges::find` on a temporary `std::string` yields `std::ranges::dangling` instead of a dangling iterator.

## What to remember

- `std::string` owns its bytes, guarantees `s[s.size()] == '\0'`, and invalidates views on reallocation or SSO moves.
- Pass `std::string_view` and `std::span` **by value**; never assume `sv.data()` is null-terminated after slicing or substring construction.
- `const std::span<T>` freezes the span descriptor, not the elements; use `std::span<const T>` for read-only element access.
- `std::span<T, N>` stores a single pointer when the extent `N` is static, while `std::span<T>` stores `{ptr, count}`.
- Both `std::string_view` and `std::span` model `std::ranges::borrowed_range`, shifting lifetime responsibility onto the caller whose storage they borrow.

## Concept Map Outline

- **Strings, views, and spans:** Contiguous sequence types divide into heap-capable owners and lightweight non-owning pointer-length descriptors.
  - **std::string ownership:** Owns a contiguous character buffer uniquely with a guaranteed trailing null terminator.
    - **Small String Optimization:** Short strings live inline inside the object footprint, avoiding heap allocation.
      - **Move invalidation:** Moving an SSO string copies inline bytes, leaving prior views pointing at the source.
    - **Trailing null invariant:** Since C++11, data()[size()] is always CharT(), shared identically by c_str().
    - **resize_and_overwrite:** C++23 method lets C APIs populate capacity directly without pre-zeroing memory.
  - **std::string_view borrowing:** Trivially copyable two-word descriptor of read-only characters passed by value.
    - **Missing null terminator:** Slicing via remove_suffix does not write a null byte, making printf with data() unsafe.
    - **Dangling lifetimes:** Binding a view to a temporary std::string dangles immediately at the semicolon.
    - **Deleted nullptr ctor:** C++23 deletes basic_string_view(nullptr_t) to turn null construction into a compile error.
  - **std::span descriptors:** Non-owning contiguous range wrapper generalizing pointer and count for any element type.
    - **Static vs dynamic extent:** Static extent span<T, N> stores one pointer, whereas dynamic span<T> stores pointer and count.
    - **Shallow constness:** const span<T> allows mutating elements; write span<const T> for read-only views.
    - **Raw byte views:** as_bytes and as_writable_bytes reinterpret contiguous elements as std::byte spans.
  - **API boundary rules:** Return owning containers upward and pass non-owning views downward by value.
    - **borrowed_range opt-in:** Both string_view and span satisfy borrowed_range so range algorithms return real iterators.
    - **Slicing subranges:** Use first, last, and subspan to narrow views in constant time without allocations.

## Standardese Quiz Questions

### Question 1 [warmup] ([span.overview], [views.span])

Assuming 64-bit pointers (8 bytes) and std::size_t (8 bytes), what are the sizes of std::span<int, 4> and std::span<int>?

```cpp
#include <span>
constexpr auto a = sizeof(std::span<int, 4>);
constexpr auto b = sizeof(std::span<int>);
```

A. a is 8 bytes (pointer only) and b is 16 bytes (pointer plus count)
B. Both are 16 bytes because every span stores pointer and count
C. a is 16 bytes (4 ints inline) and b is 16 bytes
D. a is 24 bytes and b is 16 bytes

**Answer (A):** a is 8 bytes (pointer only) and b is 16 bytes (pointer plus count)

**Why:** A static-extent std::span<int, 4> encodes the length 4 in its type, so it only needs to store a single T* pointer (8 bytes). A dynamic-extent std::span<int> stores both T* and std::size_t (16 bytes).

### Question 2 [warmup] ([span.elem], [views.span])

What does the const qualifier on the parameter const std::span<int> s enforce inside the function?

```cpp
void tweak(const std::span<int> s) {
    if (!s.empty()) s[0] = 42;
}
```

A. Compilation fails because s is const and cannot modify elements
B. s[0] returns a prvalue copy, leaving the caller's array unchanged
C. Compilation succeeds and s[0] modifies the caller's underlying int
D. Compilation fails unless s is passed by const reference

**Answer (C):** Compilation succeeds and s[0] modifies the caller's underlying int

**Why:** const on std::span<int> is shallow: it prevents reassigning s itself inside tweak, not mutating the elements it refers to. Read-only element access requires std::span<const int>.

### Question 3 [tricky] ([string.view.modifiers], [string.view.access])

What is the bug in passing sv.data() to std::puts after slicing with remove_suffix?

```cpp
#include <cstdio>
#include <string_view>

void print_prefix(std::string_view sv) {
    sv.remove_suffix(4);
    std::puts(sv.data());
}
```

A. remove_suffix reallocates the underlying buffer without a terminator
B. sv.data() still points to the full original string (or non-null-terminated memory), so std::puts prints past the slice or causes undefined behavior
C. std::string_view::data() returns nullptr after remove_suffix
D. remove_suffix throws std::out_of_range if sv is shorter than 4 characters

**Answer (B):** sv.data() still points to the full original string (or non-null-terminated memory), so std::puts prints past the slice or causes undefined behavior

**Why:** std::string_view::remove_suffix only decrements the internal length without copying bytes or writing a null terminator. Thus sv.data() still points at the unsliced buffer—printing the removed suffix too or overrunning if the original view was not null-terminated.

### Question 4 [tricky] ([string.require], [string.cons])

What happens to sv after moving a short SSO std::string a into b?

```cpp
std::string a = "hello";
std::string_view sv = a;
std::string b = std::move(a);
```

A. sv automatically updates to point into b's buffer
B. sv still safely observes "hello" inside b because move steals a heap pointer
C. std::string_view pins a's buffer via reference counting until sv is destroyed
D. Moving a short SSO string copies inline bytes and invalidates pointers, references, and views into a; sv no longer refers to b and reading it is invalid

**Answer (D):** Moving a short SSO string copies inline bytes and invalidates pointers, references, and views into a; sv no longer refers to b and reading it is invalid

**Why:** Under [string.require], moving a std::basic_string invalidates pointers, references, and iterators into the moved-from string. For short strings using SSO, the characters reside directly inside a's footprint and must be copied into b, leaving sv disconnected from b.

### Question 5 [standardese] ([string.view.cons])

How does C++23 treat the initialization std::string_view sv = nullptr; compared to C++17?

```cpp
#include <string_view>
std::string_view sv = nullptr;
```

A. In C++17 it selects the const char* constructor causing UB; in C++23 it is ill-formed because the nullptr_t constructor is explicitly deleted
B. In both C++17 and C++23 it constructs an empty string_view with size 0
C. In C++23 it throws std::logic_error at runtime
D. In both C++17 and C++23 it is ill-formed due to ambiguous overloads

**Answer (A):** In C++17 it selects the const char* constructor causing UB; in C++23 it is ill-formed because the nullptr_t constructor is explicitly deleted

**Why:** In C++17/C++20, nullptr converted to const char* and invoked basic_string_view(const CharT*), calling Traits::length(nullptr) (UB). C++23 (P2166R1) added basic_string_view(std::nullptr_t) = delete; in [string.view.cons] so it is diagnosed at compile time.

### Question 6 [standardese] ([string.access], [string.require])

Given std::string s = "abc";, what does evaluating s[s.size()] produce in C++11 and later?

```cpp
std::string s = "abc";
char c = s[s.size()];
```

A. Undefined behavior because s.size() is out of bounds
B. Throws std::out_of_range
C. Well-defined: returns a reference to CharT() ('\0'), though writing a non-null value through a non-const reference to s[s.size()] is undefined behavior
D. Well-defined only when s is const-qualified

**Answer (C):** Well-defined: returns a reference to CharT() ('\0'), though writing a non-null value through a non-const reference to s[s.size()] is undefined behavior

**Why:** Since C++11, [string.access] guarantees that both const and non-const operator[](size()) return a reference to CharT() (the null terminator). Reading s[s.size()] is well-defined, while modifying it to any value other than CharT() is undefined behavior.

# Strings and string_view

> std::string owns a contiguous, always null-terminated buffer and invalidates like a vector. std::string_view is a non-owning pointer and length pair, not null-terminated, whose main hazard is outliving the thing it looks at.

- **Source:** C++ Atlas (https://cppatlas.com/topics/strings-and-string-view)
- **Track:** Containers and strings
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [basic.string] (https://eel.is/c++draft/basic.string), [string.require] (https://eel.is/c++draft/string.require), [string.access] (https://eel.is/c++draft/string.access), [string.capacity] (https://eel.is/c++draft/string.capacity), [string.cons] (https://eel.is/c++draft/string.cons), [string.view] (https://eel.is/c++draft/string.view), [string.view.cons] (https://eel.is/c++draft/string.view.cons), [char.traits] (https://eel.is/c++draft/char.traits)
- **cppreference links:** [std::basic_string](https://en.cppreference.com/w/cpp/string/basic_string), [std::basic_string::resize_and_overwrite](https://en.cppreference.com/w/cpp/string/basic_string/resize_and_overwrite), [std::basic_string_view](https://en.cppreference.com/w/cpp/string/basic_string_view), [std::char_traits](https://en.cppreference.com/w/cpp/string/char_traits)
- **Prerequisites:** iterator-invalidation, reference-binding-and-temporaries

## The one idea

`std::string` and `std::string_view` are two answers to different questions. A `string` answers "who owns these characters?" It owns a heap or inline buffer, frees it, and can grow it. A `string_view` answers "where are these characters?" It is a pointer and a length, nothing more, and it says nothing about how long the characters will stay there.

Everything else follows. A `string` behaves like a `vector<char>` with a terminator: contiguous, reallocating, invalidating. A `string_view` behaves like a borrowed reference that you can copy cheaply, slice for free, and accidentally leave dangling.

> **Mental model.** A `string` is a buffer you own. A `string_view` is a borrowed window onto someone else's buffer. Copy the window as much as you like, but the owner must outlive every use of it.

## What `std::string` guarantees

The characters are stored contiguously, so `&s[0] + n == &s[n]` for every valid `n`, and `data()` can be handed to any C API that wants a pointer and a length. Since C++11 the buffer is also always null-terminated: `data()` and `c_str()` are the same function, and `data()[size()]` is a valid read that yields `'\0'`. This is why `s[s.size()]` is legal for reading, and why `at(s.size())` still throws `std::out_of_range`.

```cpp
#include <string>

void demo() {
  const std::string s = "abc";
  char c = s[s.size()];       // OK: reads the terminator, c == '\0'
  // s.at(s.size());          // throws std::out_of_range
  // s[s.size() + 1];         // undefined behavior
  (void)c;
}
```

The terminator is yours to read, not to change. For the non-const `operator[]`, writing anything other than `'\0'` to position `size()` is undefined behavior. Embedded null characters are fine, but then `c_str()` is only a C string up to the first one.

> **Standardese.** [string.access] says `operator[]` with `pos == size()` returns a reference to an object with value `charT()`, and that modifying it to any other value is undefined behavior. [string.require] requires the range `[data(), data() + size()]` to be valid, with the terminator at the end.

### Small string optimization is practice, not promise

Every mainstream implementation stores short strings inside the `string` object itself, so no allocation happens for them. The thresholds differ. On this 64-bit machine, libstdc++ keeps up to 15 characters inline in a 32-byte object, and libc++ keeps up to 22 in a 24-byte object. The standard promises neither number, and it does not even mention the optimization. What it does promise is that `capacity()` is at least `size()`, and `reserve` and `shrink_to_fit` obey their usual rules.

The practical consequence is that "pointer into a short string" is a pointer into the string object. Move it, swap it, or let it be destroyed, and the pointer goes with it. Never reason that a short string is "safe" because it did not allocate; follow the invalidation rules instead.

### Invalidation

Pointers, references and iterators into a `string` can be invalidated by any standard function that takes the string by non-const reference (`std::swap`, `std::getline`, `operator>>`) and by calling any non-const member function except `operator[]`, `at`, `data`, `front`, `back` and the `begin`/`end` family. In practice that means growth, `insert`, `erase`, `clear` and `reserve` should all be assumed to invalidate. This is close to the rule for `vector`, and the topic on iterator invalidation covers the machinery.

## `resize_and_overwrite`, `npos` and the new queries

Before C++23, filling a string from a C API meant `s.resize(n)`, which writes `n` zero bytes, and then overwriting them. `resize_and_overwrite(count, op)` hands your callable a pointer to storage for `count` characters and uses the integer it returns as the new size. The characters in the buffer beyond what you had before are indeterminate, so you must write every one you report.

```cpp
#include <cstdio>
#include <string>

std::string format_int(int v) {
  std::string s;
  s.resize_and_overwrite(12, [v](char* p, std::size_t n) {
    // snprintf writes the digits and a terminator, and returns the length
    return static_cast<std::size_t>(std::snprintf(p, n + 1, "%d", v));
  });
  return s;
}
```

The callable must not throw, must not modify `p` or `count`, and must return a value in `[0, count]`. Returning a length that includes characters you never wrote is undefined behavior, because the string would read indeterminate values. Every iterator, pointer and reference into the string is invalidated, even if no reallocation happened.

`std::string::npos` is `static_cast<size_type>(-1)`, the largest value of the unsigned size type. Every `find` family function returns it on failure, and it doubles as "until the end" for a length argument, so `s.substr(pos)` is the same as `s.substr(pos, npos)`. The recurring bug is treating the result as a signed index:

```cpp
#include <string>

void idioms(const std::string& s) {
  if (s.find('/') != std::string::npos) { /* found */ }
  std::size_t i = s.find('/');
  std::size_t next = i + 1;  // 0 when i == npos: unsigned wraparound
  (void)next;
}
```

When you only need a yes or no, C++20 gave `starts_with` and `ends_with`, and C++23 gave `contains`, each taking a character, a `string_view` or a C string. They say what you mean without an `npos` comparison.

## What `std::string_view` is

A `string_view` holds a `const char*` and a length. It is trivially copyable, `constexpr` throughout, and constructing one never allocates or copies characters. It can be built from a `std::string`, from a C string (which costs a `strlen`), from a pointer and length, and since C++23 from any contiguous range of `char` through an explicit constructor. Constructing one from `nullptr` is deleted in C++23.

```cpp
#include <string>
#include <string_view>

void view_basics() {
  std::string s = "hello";
  std::string_view sv = s;        // no copy, points at s's buffer
  s[0] = 'J';                     // sv now sees "Jello"
  sv.remove_prefix(1);            // moves sv's start; s is untouched
  std::string_view tail = sv.substr(1);  // O(1), unlike std::string::substr
  (void)tail;
}
```

Two properties set it apart from a `string`. First, a view has no terminator of its own: `sv.data()[sv.size()]` is not guaranteed to be anything, and in a slice such as `sv.substr(0, 5)` the byte after the end is simply the next character of the original text. Passing `data()` to a function expecting a C string reads past the view, as the next example does.

```cpp
#include <cstdio>
#include <string_view>

void leak() {
  std::string_view whole = "hello world";
  std::string_view w = whole.substr(0, 5);
  std::printf("%s\n", w.data());  // prints "hello world", not "hello"
}
```

Second, it does not own. The characters belong to whatever the view was made from, and the view's lifetime must fit inside theirs.

> **Pitfall.** Initializing a view from an expression that creates a temporary string leaves the view dangling at the end of the full expression. `std::string_view sv = s + "x";` compiles, and every later use of `sv` is undefined behavior. Neither GCC nor Clang rejects it by default, though recent Clang warns about some forms, and constant evaluation catches it.

```cpp
#include <string>
#include <string_view>

std::string name();

void dangling() {
  std::string_view a = name();            // dangling: the temporary dies at the semicolon
  std::string s = "abc";
  std::string_view b = s + "x";           // dangling for the same reason
  std::string_view ok = s;                // fine while s lives and is not reallocated
  (void)a; (void)b; (void)ok;
}
```

A view also dangles when its owner is modified: `s += "more"` may reallocate and leave `ok` pointing at freed memory, which is the same invalidation rule as for pointers.

## Conversions and parameters

`std::string` converts to `std::string_view` implicitly, through a conversion operator on `string`. The other direction is explicit, through a constructor template on `string`. The asymmetry is about cost and honesty: the first conversion is free and cannot fail, while the second allocates and copies, and the language lets you hide neither.

```cpp
#include <string>
#include <string_view>

void takes_view(std::string_view);
void takes_string(const std::string&);

void conv(std::string s, std::string_view v) {
  takes_view(s);                    // implicit, free
  // std::string t = v;             // ill-formed: explicit constructor
  std::string t{v};                 // OK: allocates and copies
  s = v;                            // OK: assignment from a view is provided directly
  s += v;                           // OK
  // takes_string(v);               // ill-formed for the same reason as above
  takes_string(std::string(v));     // OK
}
```

That shapes how functions should take text. A parameter of type `const std::string&` forces a temporary `string` for every string literal and every view the caller holds, and that construction allocates once the text exceeds the small-string capacity. A `std::string_view` parameter accepts a `string`, a literal and a view with no allocation. Use `string_view` for read-only parameters, and keep `std::string` when the function stores the text, because storing a view stores a promise someone must keep.

A view parameter is wrong when the callee needs a terminator, as C APIs do. A `const std::string&` or `const char*` is the honest type there. It is also a trap to store a view in a member, unless the owner's lifetime is guaranteed to cover it.

There is no `operator+` between a view and a C string, so `sv + "c"` is ill-formed. C++26 adds overloads that accept one `string` and one `string_view` operand, but still nothing for two views.

## Literals and `char_traits`

The suffix `s` in `"abc"s` makes a `std::string`, and `sv` in `"abc"sv` makes a `std::string_view` whose length is known at compile time, so even a literal with embedded nulls keeps all its characters. Both live in `std::literals` and need a `using namespace std::literals;` or a more specific using-directive. Prefer `sv` for constants, because a `constexpr std::string_view` never allocates and can be used in constant expressions.

Both classes are really `basic_string<CharT, Traits, Allocator>` and `basic_string_view<CharT, Traits>`. `char_traits` supplies the character comparison, copy and length operations, which is why `std::string` and `std::u8string` are the same template with different parameters, and why a case-insensitive string is a different type, not a flag. Different traits mean different, non-interchangeable types.

## What to remember

- `string` owns and reallocates like `vector`; `string_view` is a non-owning pointer and length.
- Since C++11 `data()` and `c_str()` are the same, and `data()[size()]` is a readable `'\0'`; writing anything else there is undefined.
- Small string optimization is an implementation habit with different thresholds; rely on the invalidation rules, not on "short strings do not move".
- `resize_and_overwrite` (C++23) avoids zero-filling, but every reported character must be written and the callable must not throw.
- `find` returns `npos`, an unsigned maximum; adding one to it wraps to zero. Prefer `starts_with`, `ends_with` and `contains` for yes or no questions.
- A `string_view` is not null-terminated, and a view initialized from a temporary string, such as `s + "x"`, dangles at the end of the statement.
- `string` converts to `string_view` implicitly; the reverse is explicit, because it allocates.
- Take `string_view` for read-only text, `std::string` for text you keep, and a `const char*` or `const std::string&` when a terminator is required.

## Concept Map Outline

- **Strings and string_view:** An owning buffer versus a borrowed window onto characters.
  - **std::string guarantees:** Contiguous, null-terminated storage with vector-like growth and invalidation.
    - **Contiguous storage:** data() works with any pointer-and-length API.
    - **Null terminator (C++11):** data()[size()] is readable and equals the null character; writing another value is undefined.
    - **Invalidation:** Non-const members other than operator[], at, data, front, back and begin/end may invalidate.
  - **Small string optimization:** An implementation habit, not a standard promise.
    - **Inline short strings:** libstdc++ holds 15 chars, libc++ 22 on 64-bit; the standard names neither.
    - **Pointers move with object:** Pointers into a short string point into the string object itself.
  - **Modern string API:** Newer members that say what you mean.
    - **resize_and_overwrite (C++23):** Skips zero-fill; every character you report must be written, and the callable must not throw.
    - **npos idioms:** npos is the unsigned maximum, so npos + 1 wraps to zero.
    - **starts_with, contains:** C++20 starts_with and ends_with, C++23 contains, avoid npos comparisons.
  - **std::string_view:** A non-owning pointer and length.
    - **Not null-terminated:** data()[size()] is not guaranteed; slices continue into the original text.
    - **Cheap slicing:** substr, remove_prefix and remove_suffix are O(1) and copy nothing.
    - **Dangling from temporaries:** A view built from s + "x" outlives the temporary and is undefined to read.
    - **Borrowed range:** A string_view is both a view and a borrowed range.
  - **Conversions and parameters:** Implicit one way, explicit the other.
    - **string to view implicit:** A conversion operator on string; free and cannot fail.
    - **view to string explicit:** A constructor that allocates; assignment and += from a view still work.
    - **Choosing parameter types:** string_view for read-only text, string to store it, const char* if terminator needed.
  - **Literals and traits:** Suffixes and the template behind the names.
    - **"x"s and "x"sv:** The s suffix makes a string, sv a view with known length, in std::literals.
    - **char_traits:** Supplies comparison and copy; different traits give different types.
    - **No view + view:** There is no operator+ for two views; C++26 adds string and view mixes.

## Standardese Quiz Questions

### Question 1 [warmup] ([string.cons], [basic.string])

Which statement in `main` is ill-formed in C++23?

```cpp
#include <string>
#include <string_view>

void takes_view(std::string_view);

int main() {
  std::string s = "text";
  std::string_view v = s;
  takes_view(s);          // (1)
  std::string a{v};       // (2)
  std::string b = v;      // (3)
  s = v;                  // (4)
}
```

A. (1), because string to string_view needs a cast
B. (2), because the string constructor from a view is deleted
C. (3), because the constructor taking a view is explicit
D. (4), because string has no assignment from a view

**Answer (C):** (3), because the constructor taking a view is explicit

**Why:** `std::string` converts to `std::string_view` through a conversion operator, so (1) is fine. The constructor from a view-like object is `explicit`, so direct-initialization in (2) works but copy-initialization in (3) is rejected. Assignment from a view is provided as its own overload, which is why (4) compiles even though (3) does not.

### Question 2 [warmup] ([string.view], [string.require])

What does this program print?

```cpp
#include <iostream>
#include <string>
#include <string_view>

int main() {
  std::string t = "hello";
  std::string_view sv = t;
  t[0] = 'J';
  std::cout << sv << '\n';
}
```

A. `hello`, because the view copied the characters
B. `Jello`
C. Undefined behavior, because the string was modified while a view existed
D. The program is ill-formed

**Answer (B):** `Jello`

**Why:** A `string_view` is a pointer and a length into `t`; it copies nothing. Writing through `operator[]` neither reallocates nor invalidates anything, so the view simply observes the new character. The view would only be at risk if `t` were modified in a way that can reallocate.

### Question 3 [warmup] ([string.capacity], [basic.string])

What does this program print?

```cpp
#include <iostream>
#include <string>

int main() {
  std::string s = "abc";
  std::size_t i = s.find('z');
  std::cout << (i + 1) << '\n';
}
```

A. `0`
B. `-1`
C. `4`
D. Undefined behavior

**Answer (A):** `0`

**Why:** `find` returns `std::string::npos`, which is `static_cast<size_type>(-1)`. `size_type` is unsigned, so adding one wraps around to zero, and unsigned wraparound is well-defined. The value `-1` is not representable in an unsigned type, which rules out the second option.

### Question 4 [tricky] ([string.view], [string.view.cons])

What does this program print?

```cpp
#include <cstdio>
#include <string_view>

int main() {
  std::string_view whole = "hello world";
  std::string_view w = whole.substr(0, 5);
  std::printf("%s\n", w.data());
}
```

A. `hello`
B. `hello world`
C. Undefined behavior, because `w.data()` is not null-terminated
D. Unspecified: it depends on the implementation

**Answer (B):** `hello world`

**Why:** `w` points into the same literal as `whole`, and `data()` returns that pointer without any terminator being added at the end of the slice. `printf` reads until the next `'\0'`, which is the literal's own terminator, so the whole text is printed. The read is well-defined here only because the underlying array is null-terminated; a view onto an unterminated buffer would read out of bounds.

### Question 5 [tricky] ([string.access])

What does this program print?

```cpp
#include <iostream>
#include <string>

int main() {
  const std::string s = "abc";
  std::cout << (s[s.size()] == '\0') << ' ';
  try {
    (void)s.at(s.size());
    std::cout << "no throw";
  } catch (const std::out_of_range&) {
    std::cout << "out_of_range";
  }
  std::cout << '\n';
}
```

A. `0 out_of_range`
B. Undefined behavior from `s[s.size()]`
C. `1 out_of_range`
D. `1 no throw`

**Answer (C):** `1 out_of_range`

**Why:** Since C++11, `operator[]` accepts `pos == size()` and returns a reference to the terminating `charT()`, so the comparison is true. `at` still checks `pos < size()` and throws `std::out_of_range`. Only `pos > size()` for `operator[]` is undefined, and writing a non-null value through the non-const version at `size()` is undefined too.

### Question 6 [tricky] ([class.temporary], [string.view])

What can be said about the second line of `use`?

```cpp
#include <iostream>
#include <string>
#include <string_view>

void use(const std::string& s) {
  std::string_view sv = s + "x";
  std::cout << sv << '\n';
}
```

A. It prints `s` followed by `x`, because the view extends the temporary's lifetime
B. Undefined behavior: the string temporary is destroyed at the end of the first line
C. It does not compile, because `string_view` cannot be built from a temporary
D. Well-defined only for strings short enough for small string optimization

**Answer (B):** Undefined behavior: the string temporary is destroyed at the end of the first line

**Why:** `s + "x"` creates a temporary `std::string`, and a conversion to `string_view` binds no reference, so lifetime extension does not apply. The temporary dies at the end of the full expression and `sv` then points into destroyed storage. Small string optimization does not help: the string object itself is the destroyed thing, and the standard says nothing that would make reading it valid.

### Question 7 [standardese] ([string.cons], [string.view.cons])

In C++23, what is the status of `std::string s(nullptr);`?

```cpp
#include <string>

int main() {
  std::string s(nullptr);
}
```

A. Undefined behavior, as for a null `const char*`
B. Well-formed, and `s` is empty
C. Implementation-defined
D. Ill-formed: the constructor taking `nullptr_t` is deleted

**Answer (D):** Ill-formed: the constructor taking `nullptr_t` is deleted

**Why:** C++23 (P2166) added `basic_string(nullptr_t) = delete`, so the call is diagnosed at compile time. Before that, `nullptr` converted to `const char*` and the call was undefined behavior because the pointer was not a valid null-terminated string. The same deletion exists for `basic_string_view`.

### Question 8 [standardese] ([string.capacity])

In C++23, what does the standard say about this call?

```cpp
#include <string>

int main() {
  std::string s;
  s.resize_and_overwrite(16, [](char* p, std::size_t n) {
    p[0] = 'a';
    p[1] = 'b';
    return n;
  });
}
```

A. `s` has size 16; the last 14 characters are value-initialized
B. `s` has size 2, because only two characters were written
C. Undefined behavior: the callable reported 16 characters but wrote only 2
D. Ill-formed, because the callable must return `void`

**Answer (C):** Undefined behavior: the callable reported 16 characters but wrote only 2

**Why:** `resize_and_overwrite` makes the string exactly as long as the integer the callable returns, and the characters of that range must all hold determinate values. The buffer beyond the old contents is indeterminate, and the callable wrote only two of the 16 it reported, so the string would hold indeterminate characters. The size is taken from the return value, never inferred from what was written, and the callable returns the new size, not `void`.

# span and mdspan

> std::span is a non-owning pointer and length over contiguous elements, with the extent optionally fixed in the type. std::mdspan (C++23) extends the same borrowed view to several dimensions, with a layout policy for indexing and an accessor policy for element access.

- **Source:** C++ Atlas (https://cppatlas.com/topics/span-and-mdspan)
- **Track:** Containers and strings
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [views.span] (https://eel.is/c++draft/views.span), [span.cons] (https://eel.is/c++draft/span.cons), [span.sub] (https://eel.is/c++draft/span.sub), [span.objectrep] (https://eel.is/c++draft/span.objectrep), [mdspan.mdspan] (https://eel.is/c++draft/mdspan.mdspan), [mdspan.extents] (https://eel.is/c++draft/mdspan.extents), [mdspan.layout] (https://eel.is/c++draft/mdspan.layout), [mdspan.accessor] (https://eel.is/c++draft/mdspan.accessor)
- **cppreference links:** [std::span](https://en.cppreference.com/w/cpp/container/span), [std::span::subspan](https://en.cppreference.com/w/cpp/container/span/subspan), [std::as_bytes](https://en.cppreference.com/w/cpp/container/span/as_bytes), [std::mdspan](https://en.cppreference.com/w/cpp/container/mdspan), [std::extents](https://en.cppreference.com/w/cpp/container/mdspan/extents), [std::layout_stride](https://en.cppreference.com/w/cpp/container/mdspan/layout_stride), [std::default_accessor](https://en.cppreference.com/w/cpp/container/mdspan/default_accessor)
- **Prerequisites:** sequence-containers, strings-and-string-view, reference-binding-and-temporaries

## The one idea

A `std::span<T>` is a pointer and a count. It owns nothing, it never allocates, and it has no idea how long the memory behind it will live. What it adds over a bare pointer is that the count travels with it, and that it is a range, so it works with range-for and with the range algorithms. A `std::mdspan` is the same idea with a rank: a pointer plus a description of how a tuple of indices maps to an offset.

Both are views, which means the two questions to ask are always "what do I point at?" and "does that outlive me?"

> **Mental model.** A `span` is `string_view` for any contiguous element type, writable unless you say `const`. An `mdspan` is a `span` that has learned to count in two or more dimensions.

## Extent and size of the object

The second template argument, the **extent**, is either a number or `std::dynamic_extent`. A dynamic extent stores the length at run time, and a static extent bakes it into the type, so `span<int, 4>` needs no stored length. In the implementations tested here that makes `span<int>` the size of two pointers and `span<int, 4>` the size of one. The standard does not specify those sizes, but a static extent is allowed to be smaller, and every mainstream library takes advantage.

Static extent is a promise that the compiler can use. It also changes which conversions are implicit. The rule of thumb is that anything that loses nothing is implicit, and anything that asserts a length is explicit.

```cpp
#include <array>
#include <span>
#include <vector>

void conversions(std::vector<int>& v, int (&arr)[4], std::array<int, 4>& a4) {
  std::span<int> d1 = v;                // implicit: dynamic extent from any range
  std::span<int, 4> s1 = arr;           // implicit: array bound checked at compile time
  std::span<int, 4> s2 = a4;            // implicit: std::array size checked at compile time
  std::span<int> d2 = s1;               // implicit: dropping the static extent
  std::span<int, 4> s3(v);              // explicit: asserts v.size() == 4
  std::span<int, 2> s4(d2.first(2));    // explicit: static from dynamic
  // std::span<int, 4> bad = v;         // ill-formed: copy-initialization of a static extent
  // std::span<int, 2> bad2(s1);        // ill-formed: 4 and 2 never match
  (void)d1; (void)s2; (void)s3; (void)s4;
}
```

The explicit cases carry a precondition. `std::span<int, 4> s3(v)` is undefined behavior if `v.size() != 4`, because a range cannot be checked at compile time. Passing a `std::array<int, 3>` is a compile error instead, since its size is part of its type.

Class template argument deduction follows the source: `std::span s(arr)` for `int arr[4]` gives `span<int, 4>`, while `std::span s(vec)` gives `span<int>`.

## Constness is shallow

`const std::span<int>` is a constant view, not a view of constants. Like a `T* const`, it cannot be rebound to different elements, but the elements are still writable. To forbid writes you change the element type.

```cpp
#include <span>
#include <vector>

void shallow(std::vector<int>& v) {
  const std::span<int> cs = v;
  cs[0] = 42;                      // OK: the elements are int
  std::span<const int> ro = v;     // read-only view of the same data
  // ro[0] = 1;                    // ill-formed
  std::span<const int> from_mutable = cs;   // OK: adding const is implicit
}
```

The same logic governs construction from a range. A `span<int>` cannot be built from a `const vector<int>`, because that would drop `const`. A `span<const int>` can be built from either.

A span also makes a good function parameter. A function taking `std::span<const int>` accepts a `vector<int>`, an `std::array<int, N>` and a built-in array alike, with no template and no copy, and it states in the signature that the function reads but does not own the data. Passing a braced list needs C++26, which added an `initializer_list` constructor.

## Slicing, preconditions and the C++26 change

`first(n)`, `last(n)` and `subspan(offset, count)` return spans over the same memory, and each has a precondition. `first(n)` and `last(n)` need `n <= size()`. `subspan` needs `offset <= size()` and, if `count` is given, `count <= size() - offset`. Equality is allowed, so `s.subspan(s.size())` is a valid empty span, while `s.subspan(s.size() + 1)` is undefined behavior. The same goes for `operator[]`, `front` and `back` on an empty span.

The template forms `first<N>()`, `last<N>()` and `subspan<Offset, Count>()` always return a static extent, even from a dynamic span. On a static-extent source the compiler checks the numbers, so `span<int, 4>::first<5>()` does not compile, but with a dynamic source the precondition is still yours.

C++26 adds hardened preconditions to the standard library, including the span accessors and slicing operations, so that an implementation in hardened mode checks them instead of reading out of bounds. What it does on violation depends on the implementation and its configuration. In a plain build the behavior is still undefined, and the checked code path is not what you get by default. On the machines used for this article, libstdc++ 16 aborted with an assertion on `s.subspan(5)` for a 3-element span, while libc++ 21 in its default mode returned a span of nonsense size. C++26 also adds `span::at`, which throws `std::out_of_range`.

> **Pitfall.** Preconditions on slicing are undefined behavior, not exceptions. A span that has been sliced past its end looks fine until it is used, and in constant evaluation the compiler is allowed to reject the program, which is a useful test harness.

## Dangling and borrowed ranges

A span does not own its elements, so it dangles when the owner dies or reallocates. The constructors reflect this. A `span<const T>` can be built from an rvalue range, because a read-only parameter is the main use case, while a `span<T>` cannot, because writing into a temporary is almost always a mistake.

```cpp
#include <span>
#include <vector>

std::span<const int> bad() {
  return std::vector<int>{1, 2, 3};   // compiles; the vector dies at the return
}

void invalidated(std::vector<int>& v) {
  std::span<int> s = v;
  v.push_back(0);      // may reallocate: s now dangles
}
```

A `span` is a **borrowed range**: its iterators stay valid even after the span object is gone, because they point at the elements, not at the span. That is why the range algorithms can return iterators into a temporary span, while they refuse to do so for a temporary `std::vector`. The topic on borrowed ranges covers this in depth.

`std::as_bytes(s)` returns a `span<const std::byte>` over the same memory, and `std::as_writable_bytes(s)` a writable one, which requires a non-const element type. The result has `s.size_bytes()` elements. These are views of the object representation, so they carry the usual aliasing rules but need no cast.

## `std::mdspan`: extents, layouts and accessors

`std::mdspan<T, Extents, Layout, Accessor>` was added in C++23. The `Extents` parameter plays the role of the span's extent, once per dimension: `std::extents<std::size_t, 3, 4>` is a fully static 3 by 4 shape, and `std::dextents<std::size_t, 2>` is two dynamic dimensions. Mixed shapes such as `extents<size_t, 3, dynamic_extent>` are allowed, and only the dynamic ones occupy storage. The first template argument is the index type.

Construction deduces the shape from the arguments, and indexing takes a comma-separated list, thanks to the C++23 multidimensional `operator[]`.

```cpp
#include <mdspan>
#include <vector>

int main() {
  std::vector<int> v(12);
  for (int i = 0; i < 12; ++i) v[i] = i;

  std::mdspan m(v.data(), 3, 4);   // dextents<size_t, 2>, layout_right
  int a = m[1, 2];                 // 6: row-major, 1 * 4 + 2
  // m[1][2];                      // ill-formed: one index for a rank-2 mdspan
  return a == 6 ? 0 : 1;
}
```

The **layout policy** maps an index tuple to an offset. The default `layout_right` is row-major, as in C arrays. `layout_left` is column-major, as in Fortran. `layout_stride` stores a stride per dimension, which lets an `mdspan` view a column, or every second row, of existing data. C++26 adds padded layouts for rows with alignment padding.

```cpp
#include <array>
#include <mdspan>

void strided(const int* data) {
  using Ext = std::dextents<std::size_t, 1>;
  std::layout_stride::mapping<Ext> col(Ext{3}, std::array<std::size_t, 1>{4});
  std::mdspan column(data + 1, col);   // elements 1, 5, 9 of a 3 by 4 row-major matrix
  (void)column;
}
```

The **accessor policy** controls how an offset turns into an element. The default accessor returns `T&` for `data_handle[i]`. A custom accessor can wrap atomics, apply a scale, or work with a handle that is not a raw pointer, which is how GPU and memory-mapped data are exposed through the same interface. An `mdspan<T>` converts implicitly to an `mdspan<const T>`.

## Sub-views and library support

Slicing an `mdspan` into a row, column or block is `std::submdspan`, which is C++26, not C++23. Each index argument is an integer, which removes that dimension, a pair or `strided_slice` range, or `std::full_extent`. The result's layout is whatever keeps the mapping exact: a row of a row-major matrix stays `layout_right`, and a column becomes `layout_stride`.

```cpp
#include <mdspan>
#include <vector>
#include <version>

#ifdef __cpp_lib_submdspan   // C++26, and only in libraries that provide it
void rows(std::vector<int>& v) {
  std::mdspan m(v.data(), 3, 4);
  auto row1 = std::submdspan(m, 1, std::full_extent);          // rank 1, layout_right
  auto col2 = std::submdspan(m, std::full_extent, 2);          // rank 1, layout_stride
  (void)row1; (void)col2;
}
#endif
```

Library support, as tested for this site: `<span>` and `<mdspan>` work in `-std=c++23` with both g++-16 (libstdc++) and Homebrew clang 21 (libc++ 21). `std::submdspan` was available only in g++-16 with `-std=c++26`, where `__cpp_lib_submdspan` is defined; the libc++ bundled with clang 21 did not define it. `mdspan` operations on out-of-range indices have a precondition, like `span`, and are covered by the same C++26 hardening.

## What to remember

- A `span` is a pointer plus a length; it owns nothing and dangles like any view.
- A static extent lives in the type, so it need not be stored, but converting a runtime size into one is explicit and carries a precondition.
- `const span<T>` is shallow: elements stay writable. Use `span<const T>` for read-only.
- `span<const T>` accepts rvalue ranges, which is convenient for parameters and dangerous for locals.
- `first`, `last`, `subspan` and `operator[]` have preconditions; violations are undefined behavior until C++26 hardened implementations check them.
- `as_bytes` and `as_writable_bytes` give a byte view of any span.
- An `mdspan` has extents, a layout policy (`layout_right` by default) and an accessor policy, and is indexed by `m[i, j]` in C++23.
- `submdspan` is C++26; an `m[i][j]` chain is not how an `mdspan` is indexed.

## Concept Map Outline

- **span and mdspan:** Non-owning views over contiguous data, one-dimensional and multidimensional.
  - **span basics:** A pointer and a length that works as a range.
    - **Non-owning:** It never allocates or frees, so it dangles if the owner dies or reallocates.
    - **Borrowed range:** Iterators into a span remain valid after the span object is gone.
    - **Deduction from source:** span s(arr) gives a static extent; span s(vec) gives a dynamic one.
  - **Extent:** Fixed in the type or stored at run time.
    - **dynamic_extent:** Length is stored in the object; the default.
    - **Static extent:** Length lives in the type, so the object can be a single pointer in practice.
    - **Explicit conversions:** Dynamic to static, and range to static, are explicit and have a size precondition.
  - **Constness:** The element type decides, not the span.
    - **Shallow const:** const span<int> still lets you write the elements.
    - **span of const:** span<const int> is read-only and accepts const containers.
    - **Rvalue ranges:** Only span<const T> may be built from an rvalue range; the result dangles.
  - **Slicing preconditions:** Out-of-range slices are undefined, not exceptions.
    - **first, last, subspan:** Each needs its count or offset within size(); offset == size() is valid.
    - **Template forms:** first<N>() and friends always return a static extent.
    - **C++26 hardening:** Hardened implementations check these preconditions; plain builds may not.
  - **Bytes view:** Object representation as bytes.
    - **as_bytes:** Returns span<const byte> over the same memory.
    - **as_writable_bytes:** Needs a non-const element type.
  - **mdspan (C++23):** A non-owning multidimensional view with policies.
    - **Extents:** Static and dynamic dimensions, plus an index type; dextents is all dynamic.
    - **Layout policy:** layout_right is row-major and the default; layout_left and layout_stride exist too.
    - **Accessor policy:** Controls element access; default_accessor returns a plain reference.
    - **m[i, j] subscript:** Multidimensional operator[]; the index count must equal the rank.
    - **submdspan (C++26):** Slices rows, columns and blocks; supported by g++-16 in C++26 mode, not libc++ 21.

## Standardese Quiz Questions

### Question 1 [warmup] ([views.span])

What does this program print?

```cpp
#include <iostream>
#include <span>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3};
  const std::span<int> cs = v;
  cs[0] = 42;
  std::cout << v[0] << '\n';
}
```

A. `42`
B. `1`
C. Nothing: the program is ill-formed because `cs` is const
D. Undefined behavior

**Answer (A):** `42`

**Why:** Constness of a `span` is shallow, like a pointer: `const std::span<int>` is a constant view, but the elements are still `int`, so `operator[]` returns `int&`. To forbid writes you need `std::span<const int>`. The program therefore compiles and prints `42`.

### Question 2 [warmup] ([span.cons])

Which line is ill-formed?

```cpp
#include <span>
#include <vector>

void f(const std::vector<int>& cr) {
  std::vector<int> v{1, 2, 3};
  std::span<const int> a = v;   // (1)
  std::span<int> b = cr;        // (2)
  std::span<int> c = v;         // (3)
  int arr[3] = {1, 2, 3};
  std::span<int, 3> d = arr;    // (4)
}
```

A. (1)
B. (2)
C. (3)
D. (4)

**Answer (B):** (2)

**Why:** A `std::span<int>` can only be built from a range whose elements are convertible without dropping `const`, and `cr` gives `const int`. Line (1) adds `const`, which is allowed, (3) is an exact match, and (4) is an array of the right static size, which converts implicitly.

### Question 3 [warmup] ([mdspan.layout.right], [mdspan.mdspan])

What does this program print?

```cpp
#include <iostream>
#include <mdspan>
#include <vector>

int main() {
  std::vector<int> v(12);
  for (int i = 0; i < 12; ++i) v[i] = i;
  std::mdspan m(v.data(), 3, 4);
  std::cout << m[1, 2] << '\n';
}
```

A. `7`
B. `6`
C. `9`
D. `5`

**Answer (B):** `6`

**Why:** The default layout is `std::layout_right`, which is row-major: the last index varies fastest, so element `[1, 2]` of a 3 by 4 view lives at offset `1 * 4 + 2 = 6`. The value `7` is what `layout_left`, the column-major layout, would give for `1 + 2 * 3`.

### Question 4 [tricky] ([span.cons], [class.temporary])

What can be said about this code in C++23?

```cpp
#include <span>
#include <vector>

int sum() {
  std::span<const int> s = std::vector<int>{1, 2, 3};
  int total = 0;
  for (int x : s) total += x;
  return total;
}
```

A. Well-formed, but the loop reads a destroyed vector: undefined behavior
B. Ill-formed: a span cannot be built from an rvalue vector
C. Well-formed and well-defined: the temporary vector's lifetime is extended
D. Well-formed and well-defined: the span copies the elements

**Answer (A):** Well-formed, but the loop reads a destroyed vector: undefined behavior

**Why:** A `span` can be built from an rvalue range only when its element type is `const` (or the range is a borrowed range), because then the usual hazard is considered acceptable, so the declaration compiles. The span stores only a pointer and a size, so no lifetime extension applies, and the vector is destroyed at the end of the declaration. The loop then reads freed memory. With `std::span<int>` the declaration would be ill-formed.

### Question 5 [tricky] ([span.sub])

`s` is a `std::span<int>` over exactly 3 elements. In C++23, which call has undefined behavior?

```cpp
#include <array>
#include <span>

void f() {
  std::array<int, 3> a{1, 2, 3};
  std::span<int> s = a;
  auto p = s.first(3);      // (1)
  auto q = s.last(0);       // (2)
  auto r = s.subspan(3);    // (3)
  auto t = s.subspan(1, 3); // (4)
}
```

A. (1)
B. (2)
C. (3)
D. (4)

**Answer (D):** (4)

**Why:** `subspan(offset, count)` requires `offset <= size()` and, when `count` is given, `count <= size() - offset`. Here `offset == 1` leaves 2 elements, so asking for 3 breaks the precondition. Calls (1) and (2) take the full size and zero, and (3) uses `offset == size()`, which is valid and gives an empty span, so it is not the off-by-one trap it looks like.

### Question 6 [tricky] ([span.sub])

What is the type of `s.first<2>()` when `s` is a `std::span<int>` with dynamic extent?

```cpp
#include <span>
#include <type_traits>

void f(std::span<int> s) {
  auto t = s.first<2>();
}
```

A. `std::span<int>`
B. Ill-formed: the template form needs a static-extent span
C. `std::span<int, 2>`
D. `std::span<int, std::dynamic_extent>`, with the 2 checked at run time

**Answer (C):** `std::span<int, 2>`

**Why:** The template overloads `first<Count>`, `last<Count>` and `subspan<Offset, Count>` always return a span with a static extent, even when the source has a dynamic one. They carry a precondition `Count <= size()`, which is not checked by the type system. The function-argument overloads such as `first(2)` return a dynamic-extent span.

### Question 7 [standardese] ([mdspan.mdspan.members])

In C++23, what is the status of `m[1][2]` below?

```cpp
#include <mdspan>
#include <vector>

int main() {
  std::vector<int> v(12);
  std::mdspan m(v.data(), 3, 4);
  int x = m[1][2];
  (void)x;
}
```

A. Ill-formed: `operator[]` of a rank-2 `mdspan` requires two indices
B. Well-formed: `m[1]` is a row view that is then subscripted
C. Undefined behavior
D. Well-formed, but returns an element of the wrong row

**Answer (A):** Ill-formed: `operator[]` of a rank-2 `mdspan` requires two indices

**Why:** C++23 allows a multidimensional `operator[]`, and `mdspan::operator[]` is constrained so that the number of indices equals the rank. `m[1]` with one index therefore has no viable overload and the program is ill-formed. A row view requires `std::submdspan`, which arrives in C++26.

### Question 8 [standardese] ([span.cons])

In C++23, what is the status of the declaration of `s`?

```cpp
#include <span>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3};
  std::span<int, 4> s(v);
}
```

A. Ill-formed: a span of static extent cannot be built from a vector
B. Well-formed, and throws `std::length_error` at run time
C. Undefined behavior: the range size must equal the static extent
D. Well-formed, and `s.size()` is 3

**Answer (C):** Undefined behavior: the range size must equal the static extent

**Why:** The range constructor for a static extent is `explicit`, so direct-initialization like this compiles, and it has the precondition that `ranges::size(r) == extent`. A vector of 3 elements violates it, which is undefined behavior and not an exception. Building `std::span<int, 4>` from an array of three ints would instead be ill-formed, because the array constructor constrains the sizes at compile time.

# Node handles and heterogeneous lookup

> Node handles (C++17) let you take a node out of a map or set, change its key or move its value, and put it back or into another container without copying or allocating. Heterogeneous lookup (C++14 ordered, C++20 unordered) lets you search by a type other than the key, so no temporary key has to be built.

- **Source:** C++ Atlas (https://cppatlas.com/topics/node-handles-and-heterogeneous-lookup)
- **Track:** Containers and strings
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [container.node] (https://eel.is/c++draft/container.node), [container.insert.return] (https://eel.is/c++draft/container.insert.return), [associative.reqmts] (https://eel.is/c++draft/associative.reqmts), [unord.req] (https://eel.is/c++draft/unord.req)
- **cppreference links:** [Node handle](https://en.cppreference.com/w/cpp/container/node_handle), [std::map::extract](https://en.cppreference.com/w/cpp/container/map/extract), [std::map::merge](https://en.cppreference.com/w/cpp/container/map/merge), [std::map::insert](https://en.cppreference.com/w/cpp/container/map/insert), [std::map::find](https://en.cppreference.com/w/cpp/container/map/find), [std::unordered_map::find](https://en.cppreference.com/w/cpp/container/unordered_map/find), [std::map::erase](https://en.cppreference.com/w/cpp/container/map/erase)
- **Prerequisites:** associative-and-unordered-containers, iterator-invalidation, allocators-and-pmr

## The one idea

The associative containers are node-based: each element lives in its own allocation. Two features exploit that, and both are about not doing work you do not need to do.

A **node handle** is an owning pointer to one detached node. You can pull a node out of a container, edit it, and push it into the same or another container by relinking pointers. No element is copied, moved, or reallocated.

**Heterogeneous lookup** is the other direction: the container's comparison or hash is allowed to accept an argument of a type other than the key, so `find("literal")` does not have to build a `std::string` just to throw it away.

> **Mental model.** A node handle is a `unique_ptr` to a map or set node, and it stops being a view of the container the moment it is extracted. Heterogeneous lookup is a promise that comparing a key with a foreign type gives the same answers as comparing keys.

## Extracting and inserting nodes

`extract` takes an iterator or a key. It unlinks the node, with no allocation and no element move, and returns a handle of type `node_type`. If the key is absent it returns an empty handle. The handle is move-only, and if it is destroyed while holding a node, it destroys the element and frees the node.

The reason this matters for maps: a `map` key is `const`, so there is normally no way to rename an element short of erasing it and inserting a copy. With a node handle the key is accessible and writable.

```cpp
#include <map>
#include <string>

void rename_key() {
  std::map<int, std::string> m{{1, "a"}, {2, "b"}};
  auto nh = m.extract(1);       // unlinked; m is now {2:"b"}
  nh.key() = 3;                 // non-const access to the key
  m.insert(std::move(nh));      // relinked at the position for 3; no allocation
  // m is {2:"b", 3:"a"}
}
```

Sets get the same benefit, since `set` elements are also `const`. A set node's `value()` is a mutable reference, so you can move an element out of a set, which nothing else allows.

```cpp
#include <memory>
#include <set>

std::unique_ptr<int> take(std::set<std::unique_ptr<int>>& s) {
  return std::move(s.extract(s.begin()).value());
}
```

> **Standardese.** [container.node] describes a node handle as owning an element and its allocator, and being empty after a move. Extraction invalidates only iterators to the extracted element. Pointers and references to it remain valid but may not be used to access the element while a handle owns it. They become usable again if the element is inserted into a container.

That last sentence is easy to misread as a promise that references are always fine. They are fine only before extraction and after reinsertion, not in between.

The node handle's `key()` and `mapped()` exist only for map nodes, and `value()` only for set nodes. All three have undefined behavior on an empty handle, and so does `get_allocator()`. Use `empty()` or `explicit operator bool` to check.

## The result of inserting a node

For a unique container (`map`, `set`, and their unordered cousins), inserting a node can fail if an equivalent key is already present. `insert(node_type&&)` returns an `insert_return_type`, an aggregate with three members: `position`, an iterator; `inserted`, a bool; and `node`, a node handle.

- If the handle was empty: `inserted` is false, `position` is `end()`, and `node` is empty.
- If insertion happened: `inserted` is true, `position` points at the new element, and `node` is empty.
- If it failed because of a duplicate: `inserted` is false, `position` points at the element that blocked it, and `node` **still owns the element you tried to insert**.

```cpp
#include <set>

void dup() {
  std::set<int> s{1, 2};
  auto nh = s.extract(1);
  s.insert(1);                        // someone else took key 1
  auto r = s.insert(std::move(nh));
  // r.inserted == false; *r.position == 1; r.node is not empty: it still owns the extracted 1
}
```

That third case is why the return type carries the node: otherwise a failed insertion would destroy the element you extracted, silently. Multiset and multimap cannot fail on duplicates, so their `insert(node_type&&)` returns a plain iterator. The hinted overload `insert(hint, nh)` also returns an iterator, and if insertion fails, the argument handle keeps ownership.

## Merging containers

`a.merge(b)` extracts every element of `b` whose key does not already exist in `a` and inserts it into `a`, using `a`'s comparator or hash. Elements with duplicate keys stay in `b`. No element is copied or moved, and pointers and references to the transferred elements remain valid, but refer into `a`. Do not keep using iterators to the transferred elements.

```cpp
#include <map>
#include <string>

void merging() {
  std::map<int, std::string> m1{{1, "a"}, {2, "b"}};
  std::map<int, std::string> m2{{2, "X"}, {3, "c"}};
  m1.merge(m2);
  // m1 is {1:"a", 2:"b", 3:"c"}; m2 is {2:"X"}: the duplicate stayed behind
}
```

The two containers may differ in comparison or hash, and a `map` can merge from a `multimap` and the reverse, as long as key, mapped type, and allocator types match. The same compatibility lets you insert a node extracted from a `std::map` into a `std::multimap`.

## Allocators

A node handle carries a copy of its source container's allocator, because it needs it for destruction. Inserting a node, and merging, requires the allocators to compare equal. The behavior is undefined otherwise, even though the code compiles.

This bites in practice with `std::pmr` containers: two `pmr::map` objects backed by different memory resources have unequal allocators, so moving a node between them is undefined behavior, even though each is a `pmr::map<int, int>`. Copy the element in that case. With the default `std::allocator`, which is always equal, the problem does not arise.

> **Pitfall.** `extract` plus `insert` across containers is a pointer splice, which only works if the node's memory can legally be freed by the destination container. Unequal allocators violate that, and the standard declares it undefined instead of making the container reallocate.

## Heterogeneous lookup

`std::map<std::string, int>` uses `std::less<std::string>`. Calling `find("a literal")` converts the argument to a `std::string`, and a long text means a heap allocation, to do one comparison. Passing a `std::string_view` does not compile at all, since there is no implicit conversion from it to `std::string`.

Since C++14, ordered containers support lookup with another type when the comparator is **transparent**: it has a nested type named `is_transparent`. `std::less<>`, which is `std::less<void>`, is transparent and forwards to `operator<` on whatever types it is given.

```cpp
#include <map>
#include <string>
#include <string_view>

void lookup() {
  std::map<std::string, int> plain;
  std::map<std::string, int, std::less<>> open;
  std::string_view key = "needle";
  // plain.find(key);          // ill-formed: no overload takes string_view
  open.find(key);              // OK: compares string_view with string directly
  open.count("literal");       // OK: no temporary std::string
}
```

The overloads that gain a template form are `find`, `count`, `contains`, `lower_bound`, `upper_bound` and `equal_range`. Declaring the map with `std::less<>` changes its type, so it cannot be assigned to `std::map<std::string, int>`.

### Unordered containers (C++20)

The unordered containers need two transparent parts: a hash and an equality predicate. `std::hash<std::string>` is not transparent, so you write your own, and the hash must give the same value for a `string_view` as for the equal `std::string`. The simple way is to hash through `string_view`:

```cpp
#include <functional>
#include <string>
#include <string_view>
#include <unordered_map>

struct StrHash {
  using is_transparent = void;
  std::size_t operator()(std::string_view s) const {
    return std::hash<std::string_view>{}(s);
  }
};

using Table = std::unordered_map<std::string, int, StrHash, std::equal_to<>>;

int get(const Table& t, std::string_view k) {
  auto it = t.find(k);                 // OK since C++20: no std::string built
  return it == t.end() ? 0 : it->second;
}
```

### Erase and extract (C++23), insertion (C++26)

C++23 added template overloads of `erase` and `extract` that take a transparent key, so `m.erase("abc"sv)` and `m.extract("abc"sv)` work. They are excluded if the argument converts to `iterator` or `const_iterator`, so `m.erase(it)` still means what it did. C++26 adds the remaining ones, `operator[]`, `at`, `try_emplace` and `insert_or_assign`.

Library support is uneven. g++-16 provides erase and extract in C++23 mode and the insertion overloads in C++26 mode. libc++ 21, bundled with Homebrew clang 21, provides the C++14 and C++20 lookup but neither of the later additions.

## Pitfalls with inconsistent comparators

Transparency is a claim, and the container takes your word for it. Three failure modes follow.

First, the comparator must accept both argument orders: lookup needs `comp(key, other)` and `comp(other, key)`. A comparator written for one order does not compile as soon as you use it for lookup.

Second, the ordering of foreign values must agree with the ordering of keys. If `comp(a, b)` says one thing about a `string_view` against a key and a different thing from the key-to-key comparison, the tree can lie about where an element would be and `find` misses elements that are present. The standard requires this partitioning, and a violation is undefined behavior, not a wrong answer.

Third, hashing: if `h("abc")` for a `const char*` is a pointer hash while `h(std::string("abc"))` hashes characters, equal keys land in different buckets and lookups fail. Make every overload of the hash agree on equal values.

## What to remember

- `extract` unlinks a node with no allocation; the handle is move-only, owns the element, and frees it if never reinserted.
- `nh.key()` is the only way to change a map key without copying; sets allow moving elements out through `value()`.
- Pointers and references to an extracted element are not usable while the handle holds it, and are usable again after reinsertion.
- `insert(node_type&&)` into a unique container returns `{position, inserted, node}`, and on a duplicate the node keeps the element.
- `merge` leaves duplicate-key elements in the source, copies nothing, and requires equal allocators.
- Inserting or merging a node across unequal allocators is undefined, as with two `pmr` containers on different resources.
- Ordered heterogeneous lookup needs a transparent comparator such as `std::less<>`; unordered needs a transparent hash and equality (C++20).
- C++23 adds heterogeneous `erase` and `extract`, and C++26 adds `operator[]`, `at`, `try_emplace` and `insert_or_assign`.
- Foreign-type comparisons and hashes must be consistent with the key ones, or lookup is undefined.

## Concept Map Outline

- **Node handles and heterogeneous lookup:** Splice nodes between containers and search without building keys.
  - **Node handles (C++17):** Move-only owners of one detached node.
    - **extract:** Unlinks a node by iterator or key with no allocation; a missing key gives an empty handle.
    - **Edit the key:** nh.key() is mutable, the only way to rename a map key without copying.
    - **Move out of a set:** nh.value() is mutable, so an element can be moved out of a set.
    - **Reference validity:** References to an extracted element are unusable while owned, valid again after insertion.
  - **Inserting nodes:** Reinsertion is a relink, not a copy.
    - **insert_return_type:** Holds position, inserted and node; the node keeps the element after a duplicate failure.
    - **Empty handle insert:** No effect: inserted is false, position is end(), node is empty.
    - **Multi containers:** Insertion cannot fail on duplicates and returns a plain iterator.
  - **merge:** Splice every non-conflicting node from another container.
    - **Duplicates stay behind:** Elements whose key exists in the destination remain in the source.
    - **Compatible containers:** Comparator or hash may differ, and map and multimap interchange.
  - **Allocator rules:** The node carries its container's allocator.
    - **Equal allocators needed:** insert and merge across unequal allocators are undefined.
    - **pmr resources differ:** Two pmr maps on different resources have unequal allocators.
  - **Heterogeneous lookup:** Search with a type other than the key.
    - **Transparent comparator:** std::less<> or any comparator with is_transparent enables template find overloads.
    - **Unordered (C++20):** Needs a transparent hash and equality, and hashes must agree across types.
    - **Erase and extract (C++23):** Template overloads take transparent keys; excluded for iterator-convertible types.
    - **Insertion forms (C++26):** operator[], at, try_emplace and insert_or_assign gain heterogeneous overloads.
  - **Pitfalls:** Transparency is a promise the container trusts.
    - **Both argument orders:** The comparator must accept key-versus-other and other-versus-key.
    - **Consistent ordering:** Foreign comparisons must agree with key ordering, or lookup is undefined.
    - **Library support:** g++-16 has C++23 erase and extract; libc++ 21 lacks them.

## Standardese Quiz Questions

### Question 1 [warmup] ([container.node], [associative.reqmts])

What does this program print?

```cpp
#include <iostream>
#include <map>
#include <string>

int main() {
  std::map<int, std::string> m{{1, "a"}, {2, "b"}};
  auto nh = m.extract(1);
  nh.key() = 3;
  m.insert(std::move(nh));
  for (const auto& [k, v] : m) std::cout << k << v << ' ';
  std::cout << '\n';
}
```

A. `1a 2b `
B. `3a 2b `
C. `2b 3a `
D. Ill-formed: a map key is const and cannot be modified

**Answer (C):** `2b 3a `

**Why:** A node handle exposes the key as a mutable `key_type&`, which is the only way to change a map key without copying. After the key becomes 3, `insert` links the node at the position for 3, so iteration visits 2 and then 3. The key being `const` inside the map is why the last option is tempting, but the handle sits outside the map.

### Question 2 [warmup] ([associative.reqmts])

Which line is ill-formed in C++20?

```cpp
#include <map>
#include <string>
#include <string_view>
using namespace std::literals;

void f() {
  std::map<std::string, int> plain;
  std::map<std::string, int, std::less<>> open;
  plain.find("abc");     // (1)
  plain.find("abc"sv);   // (2)
  open.find("abc"sv);    // (3)
  open.find("abc");      // (4)
}
```

A. (1)
B. (2)
C. (3)
D. (4)

**Answer (B):** (2)

**Why:** With `std::less<std::string>`, `find` takes a `const std::string&`. A `const char*` converts implicitly to `std::string`, so (1) compiles, though it builds a temporary. A `string_view` does not convert implicitly to `std::string`, so (2) has no viable overload. Lines (3) and (4) use the transparent `std::less<>`, which enables the template overload of `find`.

### Question 3 [warmup] ([associative.reqmts], [container.node])

What does this program print?

```cpp
#include <iostream>
#include <map>
#include <string>

int main() {
  std::map<int, std::string> m1{{1, "a"}, {2, "b"}};
  std::map<int, std::string> m2{{2, "X"}, {3, "c"}};
  m1.merge(m2);
  for (const auto& [k, v] : m1) std::cout << k << v << ' ';
  std::cout << "| ";
  for (const auto& [k, v] : m2) std::cout << k << v << ' ';
  std::cout << '\n';
}
```

A. `1a 2X 3c | `, because the source overwrites
B. `1a 2b | 2X 3c `, because merge stops at the first duplicate
C. `1a 2b 3c | `, because the duplicate is destroyed
D. `1a 2b 3c | 2X `

**Answer (D):** `1a 2b 3c | 2X `

**Why:** `merge` moves every node whose key is not already present and leaves the others in the source. Key 2 exists in `m1`, so that element stays in `m2` and `m1` keeps its own value `b`. Nothing is overwritten and nothing is destroyed, and merging continues past the duplicate.

### Question 4 [tricky] ([container.insert.return], [associative.reqmts])

What does this program print?

```cpp
#include <iostream>
#include <set>

int main() {
  std::set<int> s{1, 2};
  auto nh = s.extract(1);
  s.insert(1);
  auto r = s.insert(std::move(nh));
  std::cout << r.inserted << r.node.empty() << *r.position << '\n';
}
```

A. `111`
B. `012`
C. `011`
D. `001`

**Answer (D):** `001`

**Why:** Key 1 was inserted again before the node came back, so the second insertion fails: `inserted` is false and `position` refers to the existing element, whose value is 1. The returned `node` still owns the element that was not inserted, so `empty()` is false. That is the point of `insert_return_type`: a failed insertion does not destroy the element you extracted.

### Question 5 [tricky] ([container.node], [associative.reqmts])

What does this program print?

```cpp
#include <iostream>
#include <map>
#include <string>

int main() {
  std::map<int, std::string> m{{1, "a"}};
  std::string& r = m.at(1);
  auto nh = m.extract(1);
  m.insert(std::move(nh));
  r += "!";
  std::cout << m.at(1) << '\n';
}
```

A. `a!`
B. `a`, because extraction copied the element
C. Undefined behavior, because `extract` invalidated `r`
D. Ill-formed

**Answer (A):** `a!`

**Why:** Extraction invalidates only iterators to the element; pointers and references to it stay valid, and they may not be used while a node handle owns the element. Once the element is inserted again, they are usable and refer to the same object, so `r += "!"` modifies it. The program would have undefined behavior only if `r` were used between the `extract` and the `insert`.

### Question 6 [tricky] ([associative.reqmts])

In C++23, what is the status of this program?

```cpp
#include <iostream>
#include <map>
#include <string>
#include <string_view>
using namespace std::literals;

int main() {
  std::map<std::string, int, std::less<>> m{{"abc", 1}};
  std::cout << m.erase("abc"sv) << '\n';
}
```

A. Ill-formed: `erase` takes only a key or an iterator
B. Well-formed and prints `1`
C. Undefined behavior: the key types differ
D. Well-formed, but it prints `0` because `string_view` never equals `string`

**Answer (B):** Well-formed and prints `1`

**Why:** C++23 (P2077) added a template `erase(K&&)` overload to the associative containers, enabled when the comparator is transparent. In C++20 the call would be ill-formed, which is why the first option is tempting. The view compares equal to the stored string by value, so one element is erased. Some library versions, such as libc++ 21, did not yet implement it.

### Question 7 [standardese] ([container.insert.return], [associative.reqmts])

What does the standard say this program prints?

```cpp
#include <iostream>
#include <set>

int main() {
  std::set<int> s{1, 2};
  std::set<int>::node_type empty;
  auto r = s.insert(std::move(empty));
  std::cout << r.inserted << (r.position == s.end()) << r.node.empty() << '\n';
}
```

A. Undefined behavior: an empty node handle has no key to compare
B. `111`
C. `011`
D. `000`

**Answer (C):** `011`

**Why:** Inserting an empty node handle is specified: it has no effect and returns `inserted == false`, `position == end()` and an empty `node`. It is the accessors `key()`, `value()` and `get_allocator()` on an empty handle that are undefined. `111` is tempting for those who expect a successful no-op to report success.

### Question 8 [standardese] ([associative.reqmts], [container.node])

What is the status of the transfer of a node between these two maps?

```cpp
#include <map>
#include <memory_resource>

int main() {
  char b1[1024], b2[1024];
  std::pmr::monotonic_buffer_resource r1(b1, sizeof b1), r2(b2, sizeof b2);
  std::pmr::map<int, int> a(&r1), b(&r2);
  b[1] = 1;
  a.insert(b.extract(b.begin()));
}
```

A. Undefined behavior: the allocators do not compare equal
B. Well-formed: the node is reallocated from `a`'s resource
C. Ill-formed: `pmr::map` has no `extract`
D. Well-formed: allocators are never consulted when inserting a node

**Answer (A):** Undefined behavior: the allocators do not compare equal

**Why:** `insert(node_type&&)` requires the node handle's allocator to compare equal to the container's. A `polymorphic_allocator` compares equal only when both use the same memory resource, and these use different ones, so the precondition is violated. Nothing is reallocated: node transfer relinks the existing node, which is why the allocators must agree.

# array, bitset and vector<bool>

> std::array is a plain aggregate wrapping a C array, std::bitset is a fixed-size bit set with a proxy for single bits, and vector<bool> is a packed specialization whose proxy references make it behave unlike every other vector.

- **Source:** C++ Atlas (https://cppatlas.com/topics/array-bitset-and-vector-bool)
- **Track:** Containers and strings
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [array.overview] (https://eel.is/c++draft/array.overview), [array.zero] (https://eel.is/c++draft/array.zero), [array.creation] (https://eel.is/c++draft/array.creation), [dcl.init.aggr] (https://eel.is/c++draft/dcl.init.aggr), [bitset] (https://eel.is/c++draft/bitset), [bitset.members] (https://eel.is/c++draft/bitset.members), [vector.bool] (https://eel.is/c++draft/vector.bool), [container.requirements.dataraces] (https://eel.is/c++draft/container.requirements.dataraces)
- **cppreference links:** [std::array](https://en.cppreference.com/w/cpp/container/array), [std::to_array](https://en.cppreference.com/w/cpp/container/array/to_array), [std::bitset](https://en.cppreference.com/w/cpp/utility/bitset), [std::bitset::operator[]](https://en.cppreference.com/w/cpp/utility/bitset/operator_at), [std::vector<bool>](https://en.cppreference.com/w/cpp/container/vector_bool), [std::vector<bool>::reference](https://en.cppreference.com/w/cpp/container/vector_bool/reference)
- **Prerequisites:** sequence-containers, aggregates-and-designated-initializers, iterator-invalidation

## The one idea

These three types answer one question, "what if the size is known, or the elements are single bits?", and each gives a different cost. `std::array<T, N>` costs nothing over a C array and behaves like a value. `std::bitset<N>` stores N bits in whatever words the library likes. `std::vector<bool>` stores a dynamic number of bits and pays for the packing by not being a real container of `bool`.

> **Mental model.** `std::array` is a struct that holds `T[N]`. `std::bitset` is an integer with more than 64 bits. `std::vector<bool>` is a bitset that can grow, and its elements are not objects you can point at.

## `std::array` is an aggregate

An aggregate has no user-declared constructors, so `std::array` is initialized by aggregate initialization, with the same rules as a struct whose only member is a built-in array. Elements without an initializer are value-initialized, and the array is zero-filled where a built-in array would be. With no initializer at all, as in a local `std::array<int, 4> a;`, the ints are indeterminate.

```cpp
#include <array>

struct P { int x, y; };

void init() {
  std::array<int, 4> a{1, 2};            // a is {1, 2, 0, 0}
  std::array<int, 4> b;                  // indeterminate contents
  std::array<int, 4> c{};                // all zero
  std::array<std::array<int, 2>, 2> g{1, 2, 3, 4};  // brace elision, since C++14
  std::array<P, 2> ps{{{1, 2}, {3, 4}}};            // explicit braces also work
  // std::array<int, 3> bad{1, 2, 3, 4};            // ill-formed: too many initializers
  (void)a; (void)b; (void)c; (void)g; (void)ps;
}
```

Brace elision lets you omit the inner braces for the member array, which is why `std::array<int, 3> a{1, 2, 3}` works. Compilers may warn about missing braces for nested aggregates, but the code is valid. CTAD deduces both parameters, so `std::array a{1, 2, 3}` is `std::array<int, 3>`.

Because it is a wrapper and not a pointer, copying, assigning and comparing work on the elements, and `swap` is linear in `N`, not a pointer exchange. It is also a structural type with public data, so it works as a non-type template parameter, and it supports structured bindings through the tuple-like protocol.

### Element access, comparison and constant evaluation

`operator[]` on an `std::array` is unchecked, like a built-in array, while `at` throws `std::out_of_range`. `std::get<I>(a)` checks the index at compile time and is the form that works in templates. An `std::array` can be returned by value, compared with `==` and the ordering operators, and used freely in `constexpr` code, which is the main reason to prefer it over a built-in array. It never decays to a pointer, so to hand it to a C API you call `data()` and `size()` explicitly. The size is part of the type, so an `std::array<int, 3>` and an `std::array<int, 4>` are unrelated types, and a function that must accept any length is a template, or takes a `std::span`.

### Zero size and `to_array`

`N` may be zero. Then `begin() == end()`, `size()` is 0, and `front()` and `back()` are undefined behavior. `data()` may or may not be null, and the object itself still has a nonzero size in practice. That makes a zero-size array safe as a template edge case, and unsafe to treat as "memory you can point at".

C++20 added `std::to_array`, which turns a built-in array or braced list into an `std::array`, deducing the size. It exists because CTAD cannot convert elements to a chosen type, and cannot turn a string literal into an array of `char` that includes the terminator.

```cpp
#include <array>

void creation() {
  auto a = std::to_array({1, 2, 3});         // std::array<int, 3>
  auto b = std::to_array("ab");              // std::array<char, 3>, includes the null
  auto c = std::to_array<long>({1, 2});      // std::array<long, 2>, converts each element
  (void)a; (void)b; (void)c;
}
```

## `std::bitset`

`std::bitset<N>` has a size fixed at compile time and no iterators. Bit 0 is the least significant, and conversions follow that convention in both directions: the string `"0110"` has bits 1 and 2 set, and `to_string` prints the highest bit first.

```cpp
#include <bitset>
#include <iostream>

void bits() {
  std::bitset<4> b("0110");
  std::cout << b[1] << b[0] << ' ' << b.to_ulong() << ' ' << b.to_string() << '\n';
  // prints: 10 6 0110
  std::bitset<8> t(0x1FF);   // integer constructor truncates: 11111111
  (void)t;
}
```

A bitset supports the bitwise operators `&`, `|`, `^`, `~`, and the shifts, which shift in zeros and give an all-zero result when the count is at least `N`. `count()` reports the number of set bits, and `any()`, `all()` and `none()` answer the usual questions. It has `std::hash` and stream operators, so it works as a compact set of flags. The integer constructor keeps the low bits and drops the rest. The string constructor throws `std::invalid_argument` on any character other than `0` and `1`. `to_ulong` and `to_ullong` throw `std::overflow_error` when the value does not fit, so a wide bitset with only low bits set converts fine. They check the value, not the width.

Bounds checking is split. `test(pos)` and `set(pos)` throw `std::out_of_range` if `pos >= N`, while `operator[]` does not check, and an out-of-range subscript is undefined behavior. The non-const `operator[]` returns a small proxy, `bitset<N>::reference`, because a bit has no address. The standard says the const version returns `bool`. The libc++ 21 tested here returns a proxy type for the const one as well, so avoid depending on `auto x = cb[i]` giving a `bool`.

## `vector<bool>` is not a container of `bool`

For `std::vector<bool>` the standard provides a specialization intended to use one bit per element. Packing is the motivation, not a guarantee, but every mainstream implementation does it. A bit has no address, so `operator[]` on a non-const vector cannot return `bool&`. It returns a proxy object of class type `std::vector<bool>::reference`, which converts to `bool`, can be assigned a `bool`, and has a `flip()` member.

That makes several habitual forms break:

```cpp
#include <vector>

void proxies(std::vector<bool>& v) {
  auto x = v[0];            // x is a proxy, not a bool: it aliases element 0
  // bool& r = v[0];        // ill-formed: cannot bind a bool& to a prvalue proxy
  // bool* p = &v[0];       // ill-formed: address of a temporary proxy
  // for (auto& b : v) {}   // ill-formed: auto& cannot bind a prvalue
  for (auto&& b : v) b = true;   // OK: the forwarding reference holds the proxy
  for (bool b : v) { (void)b; }  // OK: copies the value
  bool y = v[0];            // a real copy of the value
  (void)x; (void)y;
}
```

> **Pitfall.** `auto x = v[0];` captures the proxy, not the value. If the vector later changes the element, or is reallocated or destroyed, `x` reads the new bit or dangles. Write `bool x = v[0];` when you want a snapshot.

The proxy assigns like a value and does not rebind. Given `auto a = v[0]; auto b = v[1]; a = b;`, the assignment copies the bit of element 1 into element 0. There is no `data()`, because there is no array of `bool` to point at. `v.flip()` flips every bit, and `v[i].flip()` flips one. The iterator is a random access iterator for the C++20 concepts, but its `reference` is not a real reference, so it does not meet the older Cpp17 forward iterator requirements.

### Thread safety

For every standard container except `vector<bool>`, two threads may modify different elements concurrently without a data race. `vector<bool>` is the stated exception. Setting one bit reads and writes a word that also holds neighbouring bits, so two threads writing adjacent elements race even though they touch different "elements".

> **Standardese.** [container.requirements.dataraces] requires implementations to avoid data races when different elements of the same container, excepting `vector<bool>`, are modified concurrently. [vector.bool] declares the `reference` class, with its conversion to `bool`, its assignment from `bool` and its `flip` member, as the type that `operator[]` returns.

### Alternatives

If you need real references, per-element threading, or a pointer to the elements, use `std::vector<char>`, `std::vector<std::uint8_t>` or, for a dynamic bit set, `std::deque<bool>`. For a fixed width, `std::bitset<N>` is the simpler choice, and it can be larger than any integer. For dynamic bits without the proxy trap, use a third-party `dynamic_bitset`, or keep `vector<bool>` and treat it as what it is: a bit set with a vector interface. The three types line up by what is fixed. If the length is known at compile time and you want real references, `std::array<bool, N>` spends a byte per element and behaves like any array. If the length is known and you want density, use `std::bitset<N>`, whose bit proxy is a documented part of its interface and which makes no claim to be a container. If the length changes at run time, you choose between the proxy of `vector<bool>` and the wasted bytes of `vector<char>`, and it pays to decide once, behind a type alias, instead of letting `vector<bool>` leak into generic code. Never write generic code that assumes `std::vector<T>::reference` is `T&`; it is the single exception to that rule.

## What to remember

- `std::array` is an aggregate with no constructors; missing initializers are zero, and a default-initialized local is not.
- Brace elision lets `std::array<int, 3> a{1, 2, 3}` skip the inner braces; too many initializers is ill-formed.
- A zero-size array has `begin() == end()`, undefined `front()` and `back()`, and an unspecified `data()`.
- `std::to_array` (C++20) deduces the size and can convert elements; CTAD does not.
- A `bitset` string reads the rightmost character as bit 0; `to_ulong` throws `overflow_error` if the value does not fit.
- `bitset::operator[]` is unchecked and returns a proxy; `test` and `set` throw `out_of_range`.
- `vector<bool>::operator[]` returns a proxy class, so `auto x = v[0]` aliases, `&v[0]` and `auto&` loops do not compile, and there is no `data()`.
- Adjacent elements of a `vector<bool>` race when written from different threads; other vectors do not.
- Use `vector<char>` or `vector<uint8_t>` for real references and thread-safe elements, and `bitset<N>` for a fixed width.

## Concept Map Outline

- **array, bitset, vector<bool>:** Fixed-size and bit-packed containers, and why vector<bool> is odd.
  - **std::array:** An aggregate wrapping T[N].
    - **Aggregate initialization:** No constructors; missing initializers are value-initialized, and a bare local is indeterminate.
    - **Brace elision:** array<int,3> a{1,2,3} works without inner braces; extra initializers are ill-formed.
    - **Zero size:** begin() equals end(); front() and back() are undefined; data() may be null.
    - **to_array (C++20):** Deduces size from a built-in array or list and can convert elements; CTAD cannot.
  - **Value-like behaviour:** Copies, compares and swaps elementwise.
    - **Linear swap:** swap exchanges elements one by one, unlike pointer-based containers.
    - **Structural and tuple-like:** Usable as an NTTP and with structured bindings.
  - **std::bitset:** N bits fixed at compile time, no iterators.
    - **Bit 0 is least significant:** The rightmost string character is bit 0; to_string prints the high bit first.
    - **Integer constructor truncates:** Only the low N bits of the integer are kept.
    - **to_ulong overflow:** Throws overflow_error when the value does not fit, regardless of N.
    - **Checked and unchecked access:** test and set throw out_of_range; operator[] is undefined out of range.
  - **vector<bool> proxy:** operator[] returns a class, not bool&.
    - **auto captures a proxy:** auto x = v[0] aliases the element; write bool x for a snapshot.
    - **No address or auto&:** &v[0], bool& and for (auto& b : v) do not compile; auto&& does.
    - **flip and no data():** v.flip() flips all bits, v[i].flip() one; there is no data().
  - **vector<bool> guarantees:** What the standard does and does not say.
    - **Packing not mandated:** Bit packing is the motivation but not a requirement; all major libraries pack.
    - **Data races:** Adjacent elements written by different threads race, unlike other vectors.
    - **Iterator category:** Models C++20 random_access_iterator but not Cpp17 forward iterator.
  - **Alternatives:** Pick by what you need from the elements.
    - **Real references needed:** Use vector<char> or vector<uint8_t>.
    - **Fixed width:** Use bitset<N>, which may exceed any integer width.

## Standardese Quiz Questions

### Question 1 [warmup] ([array.overview], [dcl.init.aggr])

What does this program print?

```cpp
#include <array>
#include <iostream>

int main() {
  std::array<int, 4> a{1, 2};
  std::cout << a[2] << a[3] << '\n';
}
```

A. Unspecified values, because the last two elements are not initialized
B. `00`
C. Nothing: the initializer has too few elements and the program is ill-formed
D. `12`

**Answer (B):** `00`

**Why:** `std::array` is an aggregate, so aggregate initialization applies: elements without an initializer are value-initialized, which gives zero for `int`. This is the same as for a built-in array. Indeterminate values only appear when the array is declared with no initializer at all, as in `std::array<int, 4> a;`.

### Question 2 [warmup] ([bitset.cons], [bitset.members])

What does this program print?

```cpp
#include <bitset>
#include <iostream>

int main() {
  std::bitset<4> b("0110");
  std::cout << b[1] << b[0] << ' ' << b.to_ulong() << '\n';
}
```

A. `10 6`
B. `01 6`
C. `10 9`
D. `01 9`

**Answer (A):** `10 6`

**Why:** The string is read with its rightmost character as bit 0, the way a binary literal is written, so `"0110"` has bit 1 and bit 2 set and the value is 6. That makes `b[1]` equal to 1 and `b[0]` equal to 0, printed as `10`. Reading the string left to right as indices 0 to 3 gives the reversed answers.

### Question 3 [warmup] ([vector.bool])

What does this program print?

```cpp
#include <iostream>
#include <vector>

int main() {
  std::vector<bool> v{true, false};
  auto x = v[0];
  v[0] = false;
  std::cout << x << '\n';
}
```

A. `1`, because `auto` copies the element
B. Undefined behavior: `v[0]` returns a dangling reference
C. `0`
D. Ill-formed: `auto` cannot deduce the proxy type

**Answer (C):** `0`

**Why:** `v[0]` on a non-const `vector<bool>` returns a proxy object of type `vector<bool>::reference`, and `auto` copies the proxy, not the bit. The proxy still refers to element 0 of the vector, which is now false, and it converts to `0` when printed. The proxy would dangle only if the vector were reallocated or destroyed.

### Question 4 [tricky] ([vector.bool], [stmt.ranged])

Which loop is ill-formed?

```cpp
#include <vector>

void f(std::vector<bool>& v) {
  for (auto b : v) {}          // (1)
  for (auto& b : v) {}         // (2)
  for (auto&& b : v) {}        // (3)
  for (const auto& b : v) {}   // (4)
}
```

A. (1)
B. (2)
C. (3)
D. (4)

**Answer (B):** (2)

**Why:** Dereferencing a `vector<bool>` iterator yields a prvalue proxy, and a non-const lvalue reference cannot bind to a prvalue, so `auto&` in (2) is rejected. By-value `auto` copies the proxy, a forwarding reference binds to the prvalue, and `const auto&` extends its lifetime. Loop (3) is the portable way to write generic code that modifies elements.

### Question 5 [tricky] ([container.requirements.dataraces], [vector.bool])

Both threads write different elements of each vector, and the vectors are not resized. Which has a data race?

```cpp
#include <thread>
#include <vector>

void f() {
  std::vector<bool> vb(2);
  std::vector<char> vc(2);
  std::thread t1([&] { vb[0] = true; vc[0] = 1; });
  std::thread t2([&] { vb[1] = true; vc[1] = 1; });
  t1.join();
  t2.join();
}
```

A. Neither: the threads write different elements
B. Both `vb` and `vc`
C. Only `vc`
D. Only `vb`

**Answer (D):** Only `vb`

**Why:** The standard lets different elements of a container be modified concurrently, with an explicit exception for `vector<bool>`. Its elements share words, so a write to one bit is a read-modify-write of storage that holds its neighbours, and two such writes race. The `vector<char>` elements are distinct memory locations and are safe. Use `vector<char>` or a vector of atomics, or add a lock, if threads share a boolean vector.

### Question 6 [tricky] ([vector.bool])

What does this program print?

```cpp
#include <iostream>
#include <vector>

int main() {
  std::vector<bool> v{true, false};
  auto a = v[0];
  auto b = v[1];
  a = b;
  std::cout << v[0] << v[1] << '\n';
}
```

A. `10`, because `a` was rebound to the element `b` refers to
B. `00`
C. `11`
D. `01`

**Answer (B):** `00`

**Why:** Assigning one `vector<bool>::reference` to another copies the bit it refers to into the bit it refers to, as an assignment of the values would, and does not rebind it. So `a = b` stores false into element 0, which makes both elements false. The tempting `10` treats the proxy like a pointer that can be reseated, but like a real reference it stays attached to its element.

### Question 7 [standardese] ([vector.bool])

Which statement about `std::vector<bool>` does the C++23 standard guarantee?

A. `operator[]` on a non-const `vector<bool>` returns a value of a class type, `vector<bool>::reference`
B. `sizeof(std::vector<bool>)` is smaller than `sizeof(std::vector<char>)`
C. Each element is stored in exactly one bit
D. `v.data()` returns a pointer to the packed words

**Answer (A):** `operator[]` on a non-const `vector<bool>` returns a value of a class type, `vector<bool>::reference`

**Why:** The standard declares `vector<bool>::reference` as a class with a conversion to `bool`, assignment from `bool` and a `flip` member, and that class is what `operator[]` returns. Space optimization is only the motivation: bit packing is not mandated, no `data()` exists, and no size comparison is promised, although every major implementation packs bits.

### Question 8 [standardese] ([bitset.members])

Assume `unsigned long` has 64 bits. What does the standard say happens here?

```cpp
#include <bitset>

int main() {
  std::bitset<100> b;
  b[70] = true;
  unsigned long x = b.to_ulong();
  (void)x;
}
```

A. It returns the low bits, ignoring bit 70
B. It returns `ULONG_MAX`
C. It throws `std::overflow_error`
D. Undefined behavior: the value does not fit

**Answer (C):** It throws `std::overflow_error`

**Why:** `to_ulong` throws `std::overflow_error` if the value cannot be represented as an `unsigned long`, and bit 70 is set, which cannot fit in a 64-bit `unsigned long`. It does not truncate. A bitset of 100 bits with only low bits set converts without any problem, so the check is on the value and not on the template size.

---

# Track: Iterators, algorithms and ranges

Iterator concepts, lazy range adaptors, borrowed ranges and customization point objects.

# Iterator categories and concepts

> C++ has two iterator taxonomies, the legacy named requirements from C++98 and the C++20 iterator concepts, and an iterator can sit at different levels in each. Knowing which one an algorithm consults explains why proxy iterators are random-access in one world and input-only in the other.

- **Source:** C++ Atlas (https://cppatlas.com/topics/iterator-categories-and-concepts)
- **Track:** Iterators, algorithms and ranges
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [iterator.requirements] (https://eel.is/c++draft/iterator.requirements), [iterator.concepts] (https://eel.is/c++draft/iterator.concepts), [iterator.cpp17] (https://eel.is/c++draft/iterator.cpp17), [iterator.traits] (https://eel.is/c++draft/iterator.traits), [iterator.assoc.types] (https://eel.is/c++draft/iterator.assoc.types), [iterator.operations] (https://eel.is/c++draft/iterator.operations)
- **cppreference links:** [Iterator library](https://en.cppreference.com/w/cpp/iterator), [std::iterator_traits](https://en.cppreference.com/w/cpp/iterator/iterator_traits), [std::forward_iterator](https://en.cppreference.com/w/cpp/iterator/forward_iterator), [LegacyForwardIterator](https://en.cppreference.com/w/cpp/named_req/ForwardIterator), [std::iter_value_t and related aliases](https://en.cppreference.com/w/cpp/iterator/iter_t), [std::distance](https://en.cppreference.com/w/cpp/iterator/distance)
- **Prerequisites:** pointers-arrays-and-pointer-arithmetic, concepts-and-constraints

## The one idea

An iterator category is a promise about which operations an iterator supports and what they cost. C++ has made that promise twice. The legacy **named requirements**, spelled *Cpp17InputIterator* through *Cpp17RandomAccessIterator* in the standard, date from C++98 and are checked by nobody: an iterator announces its level through a nested `iterator_category` tag, and algorithms trust the tag. The C++20 **iterator concepts**, `std::input_iterator` through `std::contiguous_iterator`, are real language concepts that the compiler checks, announced through a nested `iterator_concept` tag.

The two ladders look the same, but the rungs are defined differently. The single biggest difference is that the legacy forward iterator must return a real reference from `operator*`, and the C++20 one need not.

> **Mental model.** Every iterator has two report cards. `iterator_category` is graded under the C++98 rules, `iterator_concept` under the C++20 rules, and `std::` algorithms that predate ranges usually read the first while `std::ranges::` algorithms read the second.

## The legacy ladder

Each level adds operations and guarantees to the one below it.

```text
input        *it (read), ++it, it == j          single pass
  forward    + default-constructible, multi-pass, *it is T& or const T&
    bidirectional  + --it
      random access  + it + n, it - j, it[n], <  (all O(1))
        contiguous   + elements adjacent in memory (C++17 requirement, C++20 tag)
output       *it = v, ++it                      single pass, write only
```

The **multi-pass guarantee** is what separates input from forward. For forward iterators, `a == b` implies `++a == ++b`, and incrementing a copy does not change what the original refers to. An `std::istream_iterator` breaks this: copying it does not copy the stream, so once any copy advances, the characters it consumed are gone for everyone. That is why an algorithm like `std::search` that must revisit elements requires forward iterators, while `std::find` accepts input iterators.

The forward requirements also demand that `reference` be `T&` or `const T&`, where `T` is the value type. That clause, written for C++98, is the one proxy iterators cannot meet. Output iterators sit off to the side: they promise only that `*it = value` followed by `++it` works, and their `value_type` is usually `void`.

## The C++20 concepts

C++20 rebuilt the hierarchy on top of smaller concepts: `std::indirectly_readable`, `std::weakly_incrementable`, `std::incrementable`, and `std::sentinel_for`. The result differs from the legacy rules in ways that are deliberate.

- `std::input_iterator` does not require `==` between iterators, because the end of an input range is usually a sentinel of a different type. It does not require copyability, and postfix `++` may return `void`. A move-only generator iterator is a valid C++20 input iterator.
- `std::forward_iterator` adds `std::incrementable`, which brings in `std::regular` (copyable, default-initializable, equality comparable) and the multi-pass guarantee. It says nothing about `reference` being a language reference.
- `std::contiguous_iterator` does require `iter_reference_t<I>` to be an lvalue reference, and `std::to_address` to work, since contiguity is about real memory.

```cpp
#include <cstddef>
#include <iterator>

struct Gen {                       // move-only, no operator==
  using difference_type = std::ptrdiff_t;
  using value_type = int;
  int n = 0;
  Gen() = default;
  Gen(Gen&&) = default;
  Gen& operator=(Gen&&) = default;
  int operator*() const { return n; }
  Gen& operator++() { ++n; return *this; }
  void operator++(int) { ++n; }
};

static_assert(std::input_iterator<Gen>);     // OK in C++20
static_assert(!std::forward_iterator<Gen>);  // not copyable, so not multi-pass
```

Which tag does a concept consult? The standard defines an exposition-only alias, `ITER_CONCEPT(I)`. It uses `iterator_concept` if present, falls back to `iterator_category`, and, if `iterator_traits<I>` is the unspecialized primary template and neither member exists, assumes `random_access_iterator_tag` and lets the syntactic checks decide. Pointers are handled by the specialization `iterator_traits<T*>`, which reports `random_access_iterator_tag` as the category and `contiguous_iterator_tag` as the concept.

> **Standardese.** [iterator.concept.forward] lists the multi-pass guarantee as a semantic requirement of `std::forward_iterator`, and its only requirement on dereference is the `indirectly_readable` one inherited from input. The `T&` rule lives solely in [forward.iterators], the Cpp17ForwardIterator requirements.

## Why proxy iterators are two categories at once

`std::vector<bool>::iterator` dereferences to a proxy object, not a `bool&`. Under the C++98 rules it therefore fails the forward requirements and is, strictly, only an input iterator. Implementations nevertheless tag it `random_access_iterator_tag`, a long-standing white lie that legacy algorithms happen to tolerate. Under C++20 rules there is no lie: the iterator genuinely models `std::random_access_iterator`.

Range adaptors face the same issue honestly. A `views::transform` whose function returns by value produces elements as prvalues. Its iterator sets `iterator_concept` from the underlying range, so it can be random-access, but it sets `iterator_category` to `input_iterator_tag`, because claiming forward under C++98 rules would be false.

```cpp
#include <iterator>
#include <ranges>
#include <type_traits>
#include <vector>

std::vector<int> v{1, 2, 3};
auto t = v | std::views::transform([](int x) { return x * 2; });
using TI = std::ranges::iterator_t<decltype(t)>;

static_assert(std::random_access_iterator<TI>);    // C++20 report card
static_assert(std::is_same_v<std::iterator_traits<TI>::iterator_category,
                             std::input_iterator_tag>);  // C++98 report card
```

If the function returns a reference instead, the category is copied from the underlying iterator, except that contiguous is downgraded to random access. The same logic explains why `std::ranges::iota_view` iterators report an input category: `*it` returns an integer by value.

> **Pitfall.** Pass a transform iterator to a pre-ranges algorithm and the algorithm may treat it as single-pass. In C++20 it does not even meet the forward requirements that `std::max_element` or `std::search` state. C++23 adopted P2408, which lets algorithms that do not write through an iterator accept one that models the C++20 concept, but an implementation that dispatches on `iterator_category` may still choose the slow, step-by-step path.

## Associated types and `iterator_traits`

`std::iterator_traits<I>` exposes five legacy members: `difference_type`, `value_type`, `reference`, `pointer`, and `iterator_category`. Since C++20, if the iterator does not define them all, the primary template tries to compute them from the iterator's operations, and leaves the traits empty if it cannot recognise even an output iterator.

C++20 also added standalone aliases that are what generic code should use now:

| Alias | Meaning |
| --- | --- |
| `std::iter_value_t<I>` | the value type, with cv-qualifiers removed |
| `std::iter_reference_t<I>` | `decltype(*it)` |
| `std::iter_difference_t<I>` | the signed distance type |
| `std::iter_rvalue_reference_t<I>` | the type of `std::ranges::iter_move(it)` |
| `std::iter_common_reference_t<I>` | common reference of reference and `value_type&` |

The value type of `const int*` is `int`, not `const int`, while its reference type is `const int&`. For `std::vector<bool>::iterator`, the value type is `bool` and the reference type is the proxy class, which is exactly the split that the common reference machinery exists to bridge.

```cpp
#include <iterator>
#include <type_traits>

static_assert(std::is_same_v<std::iter_value_t<const int*>, int>);
static_assert(std::is_same_v<std::iter_reference_t<const int*>, const int&>);
static_assert(std::is_same_v<std::iter_rvalue_reference_t<int*>, int&&>);
```

These aliases read `std::indirectly_readable_traits` and `std::incrementable_traits` unless you have specialized `iterator_traits`, in which case your specialization wins.

## `advance`, `distance`, `next` and their costs

The generic iterator operations hide the category but not its cost. [iterator.operations] specifies `std::advance(it, n)` and `std::distance(first, last)` as constant time for random-access iterators and linear otherwise. `std::next` and `std::prev` are built on `advance`. Several preconditions are easy to forget:

- `std::advance` with a negative `n` requires a bidirectional iterator; for anything weaker it is undefined behavior.
- `std::distance(first, last)` requires `last` to be reachable from `first`, or, for random-access iterators, `first` reachable from `last`.
- `std::list::size()` is constant time, but `std::distance` over a list still walks every node, because a list iterator is bidirectional.

The `std::ranges` versions are concept-driven and know about sentinels. `std::ranges::distance(it, s)` is constant time whenever `s` models `std::sized_sentinel_for` its iterator, and `std::ranges::advance(it, n, bound)` stops at a bound instead of running off the end.

The legacy versions are where the two taxonomies collide in practice. With a C++20 iterator that reports a random-access concept but an input category, libc++ 21's `std::distance` increments one step at a time, while libstdc++ in GCC 16 recognises the concept and subtracts. Both are conforming. Calling `std::ranges::distance` makes the constant-time result portable.

## Output iterators

An output iterator is the write-only twin of an input iterator. `std::back_insert_iterator`, `std::ostream_iterator`, and `std::insert_iterator` are typical: `*it` returns the iterator itself, assignment through it calls `push_back` or writes to a stream, and `++it` does nothing. Their `value_type` and `reference` are `void`, so `std::iter_value_t` is not usable on them, though since C++20 `difference_type` is `std::ptrdiff_t`, so they satisfy `std::weakly_incrementable`.

The C++20 concept is `std::output_iterator<I, T>`. It takes the written type as a second parameter, because an iterator may accept some types and not others. Every mutable forward iterator is also an output iterator for its value type, but output iterators themselves guarantee only a single pass.

## What to remember

- Two taxonomies: legacy named requirements graded by `iterator_category`, and C++20 concepts graded by `iterator_concept` through `ITER_CONCEPT`.
- Multi-pass, the guarantee that copies advance independently, is what forward adds to input.
- Legacy forward requires `*it` to yield `T&` or `const T&`; `std::forward_iterator` does not, so proxy iterators can model C++20 random access.
- `views::transform` returning by value reports an input category but a random-access concept; `vector<bool>` iterators are tagged random access by convention.
- C++20 input iterators may be move-only and need not support `==`.
- `int*` reports `contiguous_iterator_tag` through `iterator_concept`, not `iterator_category`.
- Prefer `std::iter_value_t` and friends to `iterator_traits`; the value type has cv-qualifiers removed.
- `std::distance` is linear below random access, even for `std::list`; `std::ranges::distance` uses sized sentinels.

## Concept Map Outline

- **Iterator categories and concepts:** Two taxonomies: legacy named requirements tagged by iterator_category, C++20 concepts tagged by iterator_concept.
  - **Legacy ladder:** Input, forward, bidirectional, random access, contiguous; output on the side.
    - **Multi-pass:** Forward adds it: copies advance independently and a == b implies ++a == ++b.
    - **True reference rule:** Cpp17ForwardIterator requires *it to be T& or const T&, which proxies cannot meet.
    - **Tag is trusted:** Nothing checks iterator_category; vector<bool> iterators claim random access anyway.
  - **C++20 concepts:** Checked by the compiler and built from indirectly_readable, incrementable and sentinel_for.
    - **Weaker input:** input_iterator may be move-only, lack ==, and have a void postfix ++.
    - **Forward without T&:** forward_iterator needs regular and multi-pass, but any reference type.
    - **Contiguous needs lvalue:** contiguous_iterator requires an lvalue reference and working std::to_address.
    - **ITER_CONCEPT:** Reads iterator_concept, then iterator_category, else random access for primary traits.
  - **Proxy iterators:** An iterator can be random access by concept and input by category.
    - **views::transform:** By-value result: concept follows the base range, category is input_iterator_tag.
    - **vector<bool>:** Models random_access_iterator but never contiguous_iterator; reference is a proxy.
    - **Pointers:** iterator_traits<T*> reports random access category and contiguous concept.
  - **Associated types:** Prefer the C++20 aliases over iterator_traits members.
    - **iter_value_t:** cv-qualifiers removed: iter_value_t<const int*> is int.
    - **iter_reference_t:** Exactly decltype(*it), such as const int& for const int*.
    - **iter_rvalue_reference_t:** Type of ranges::iter_move(it); int&& for int*.
    - **Traits specialization wins:** A user specialization of iterator_traits overrides the computed traits.
  - **Operations and cost:** advance, distance, next and prev hide the category but not the cost.
    - **Linear below random:** std::distance on a list walks every node, even though size() is O(1).
    - **Negative advance:** Undefined behavior unless the iterator is at least bidirectional.
    - **ranges::distance:** Constant time whenever the sentinel models sized_sentinel_for.
  - **Output iterators:** Write-only and single pass, such as back_insert_iterator and ostream_iterator.
    - **void value_type:** iter_value_t is unusable, but difference_type is ptrdiff_t since C++20.
    - **output_iterator<I, T>:** Takes the written type as a parameter because acceptance depends on it.

## Standardese Quiz Questions

### Question 1 [warmup] ([iterator.concept.contiguous], [deque.overview], [vector.overview])

In C++23, which of these `static_assert`s fails?

```cpp
#include <deque>
#include <forward_list>
#include <iterator>
#include <list>
#include <vector>

static_assert(std::contiguous_iterator<std::vector<int>::iterator>);   // A
static_assert(std::contiguous_iterator<std::deque<int>::iterator>);    // B
static_assert(std::bidirectional_iterator<std::list<int>::iterator>);  // C
static_assert(std::forward_iterator<std::forward_list<int>::iterator>); // D
```

A. A: `vector` iterators are only random-access
B. B
C. C: `list` iterators are only forward
D. None of them fails

**Answer (B):** B

**Why:** A false `static_assert` makes the program ill-formed, so line B fails to compile. A `deque` supports constant-time indexing, so its iterators are random-access, but its elements live in separately allocated blocks and are not adjacent in memory, so it is not contiguous. `vector` iterators model `std::contiguous_iterator`, the C++20 concept for elements adjacent in memory. `list` is doubly linked and bidirectional, and `forward_list` is forward.

### Question 2 [warmup] ([readable.traits], [iterator.assoc.types])

What is `std::iter_value_t<const int*>`?

A. `const int`
B. `const int&`
C. `int`
D. `int&`

**Answer (C):** `int`

**Why:** The value type is the type of an object you could copy the element into, so cv-qualification is removed: `std::indirectly_readable_traits<const int*>` gives `int`. The reference type, `std::iter_reference_t<const int*>`, is `const int&`, which is the type that keeps the constness. Confusing the two is the usual mistake.

### Question 3 [warmup] ([iterator.operations], [list.overview])

For a `std::list<int>` with *n* elements, what does the standard specify as the complexity of `std::distance(l.begin(), l.end())`?

A. Constant, because `std::list::size()` is constant since C++11
B. Linear in *n*
C. Logarithmic in *n*
D. Unspecified

**Answer (B):** Linear in *n*

**Why:** `std::distance` is constant time only for random-access iterators, and it is linear otherwise. A list iterator is bidirectional, so `distance` must increment from `begin` to `end`. `std::list` does store its size, which makes `l.size()` constant time, but `distance` only sees two iterators and cannot reach the container.

### Question 4 [tricky] ([range.transform.iterator], [iterator.concept.random.access], [forward.iterators])

In C++23, which pair of results is correct for `TI`?

```cpp
#include <iterator>
#include <ranges>
#include <vector>

std::vector<int> v{1, 2, 3};
auto t = v | std::views::transform([](int x) { return x * 2; });
using TI = std::ranges::iterator_t<decltype(t)>;

constexpr bool ra = std::random_access_iterator<TI>;
using Cat = std::iterator_traits<TI>::iterator_category;
```

A. `ra` is `true`; `Cat` is `std::random_access_iterator_tag`
B. `ra` is `false`; `Cat` is `std::input_iterator_tag`
C. `ra` is `true`; `Cat` is `std::input_iterator_tag`
D. `ra` is `false`; `Cat` is `std::random_access_iterator_tag`

**Answer (C):** `ra` is `true`; `Cat` is `std::input_iterator_tag`

**Why:** The transform iterator takes its `iterator_concept` from the underlying `vector` iterator, so it models `std::random_access_iterator`: the C++20 concepts do not require `*it` to return a reference. Its `iterator_category` is computed separately under the legacy rules, and because the lambda returns `int` by value, `*it` is a prvalue and cannot meet the Cpp17ForwardIterator reference requirement. The category is therefore `std::input_iterator_tag`. Assuming both reports agree is the trap.

### Question 5 [tricky] ([iterator.concept.input], [iterator.concept.winc], [iterator.concepts.general])

In C++23, does `Gen` model `std::input_iterator`?

```cpp
#include <cstddef>
#include <iterator>

struct Gen {
  using difference_type = std::ptrdiff_t;
  using value_type = int;
  int n = 0;
  Gen() = default;
  Gen(Gen&&) = default;
  Gen& operator=(Gen&&) = default;
  int operator*() const { return n; }
  Gen& operator++() { ++n; return *this; }
  void operator++(int) { ++n; }
};

constexpr bool b = std::input_iterator<Gen>;
```

A. No: an input iterator must be copyable
B. No: an input iterator must support `==`
C. No: postfix `++` must return the iterator
D. Yes

**Answer (D):** Yes

**Why:** C++20 deliberately weakened the input-iterator requirements. `std::input_iterator` needs `std::weakly_incrementable` (movable, a signed `difference_type`, pre- and postfix `++` with postfix allowed to return anything), `std::indirectly_readable`, and an iterator concept derived from `input_iterator_tag`, which here comes from the `random_access_iterator_tag` fallback for the primary `iterator_traits` template. Copyability and `==` belong to the legacy Cpp17InputIterator requirements, which is where all three tempting answers come from.

### Question 6 [tricky] ([vector.bool], [iterator.concept.random.access], [iterator.concept.contiguous])

In C++23, which statement about `std::vector<bool>::iterator` is guaranteed?

A. It models `std::random_access_iterator` but not `std::contiguous_iterator`
B. It models `std::contiguous_iterator`, because `vector` storage is contiguous
C. It models only `std::input_iterator`, because `*it` is a proxy
D. It does not model `std::input_iterator`, because the proxy is not `bool&`

**Answer (A):** It models `std::random_access_iterator` but not `std::contiguous_iterator`

**Why:** The C++20 concepts accept proxy references: `std::indirectly_readable` only needs a common reference between the proxy and `bool&`, which exists, and nothing above it demands a language reference. So the iterator is random-access. It cannot be contiguous, because `std::contiguous_iterator` requires `iter_reference_t` to be an lvalue reference and the elements are bits, not addressable `bool` objects. The input-only answer is the verdict of the legacy Cpp17ForwardIterator rules, not the concepts.

### Question 7 [standardese] ([forward.iterators], [iterator.concept.forward])

Which of these is required by the Cpp17ForwardIterator requirements but **not** by the `std::forward_iterator` concept?

A. The multi-pass guarantee
B. Default construction
C. That `reference` is `T&` or `const T&`, where `T` is the value type
D. Equality comparison between two iterators of the same type

**Answer (C):** That `reference` is `T&` or `const T&`, where `T` is the value type

**Why:** [forward.iterators] requires the legacy `reference` type to be a language reference to the value type, which is what proxy iterators cannot satisfy. `std::forward_iterator` refines `std::input_iterator` with `std::incrementable` and `std::sentinel_for<I, I>`, which bring in default construction, equality comparison and copyability, and [iterator.concept.forward] states the multi-pass guarantee as a semantic requirement. So the other three are required by both.

### Question 8 [standardese] ([iterator.traits], [iterator.concepts.general], [iterator.concept.contiguous])

How does `std::contiguous_iterator<int*>` learn that a pointer is contiguous?

A. `std::iterator_traits<int*>::iterator_category` is `std::contiguous_iterator_tag`
B. `std::iterator_traits<int*>::iterator_concept` is `std::contiguous_iterator_tag`
C. The `ITER_CONCEPT` fallback assumes `std::contiguous_iterator_tag` for pointers
D. The concept special-cases pointer types with `std::is_pointer_v`

**Answer (B):** `std::iterator_traits<int*>::iterator_concept` is `std::contiguous_iterator_tag`

**Why:** The specialization `iterator_traits<T*>` defines `iterator_concept` as `contiguous_iterator_tag` while keeping `iterator_category` as `random_access_iterator_tag`, so old code that switches on the category is unaffected. `ITER_CONCEPT` reads `iterator_concept` first. The fallback for a missing tag is `random_access_iterator_tag`, and it applies only when `iterator_traits` is the primary template, which is not the case for pointers.

# The algorithm library

> Standard algorithms work on iterator ranges, not containers, and every requirement they state about iterators, callables and sortedness is a precondition you must meet. The ranges versions add projections, sentinels and richer return types, but keep the same contracts.

- **Source:** C++ Atlas (https://cppatlas.com/topics/algorithms)
- **Track:** Iterators, algorithms and ranges
- **Estimated reading time:** 15 minutes
- **ISO C++ clauses:** [algorithms.requirements] (https://eel.is/c++draft/algorithms.requirements), [algorithms.results] (https://eel.is/c++draft/algorithms.results), [alg.copy] (https://eel.is/c++draft/alg.copy), [alg.remove] (https://eel.is/c++draft/alg.remove), [alg.unique] (https://eel.is/c++draft/alg.unique), [alg.sorting] (https://eel.is/c++draft/alg.sorting), [alg.binary.search] (https://eel.is/c++draft/alg.binary.search), [alg.partitions] (https://eel.is/c++draft/alg.partitions), [alg.heap.operations] (https://eel.is/c++draft/alg.heap.operations)
- **cppreference links:** [Algorithms library](https://en.cppreference.com/w/cpp/algorithm), [Constrained algorithms](https://en.cppreference.com/w/cpp/algorithm/ranges), [std::remove, std::remove_if](https://en.cppreference.com/w/cpp/algorithm/remove), [std::copy, std::copy_if](https://en.cppreference.com/w/cpp/algorithm/copy), [std::lower_bound](https://en.cppreference.com/w/cpp/algorithm/lower_bound), [std::make_heap](https://en.cppreference.com/w/cpp/algorithm/make_heap)
- **Prerequisites:** iterator-categories-and-concepts, lambdas

## The one idea

An algorithm sees two iterators and, sometimes, a function object. It never sees the container. That single fact explains most surprises: `std::remove` cannot shrink a vector, `std::sort` cannot work on a `std::list`, and nothing stops you from handing an algorithm a range it was never meant to accept.

Everything the algorithm needs from you is a precondition. The iterator category, the sortedness of the input, the purity of a predicate, the non-overlap of source and destination: break any of them and the standard owes you nothing, usually undefined behavior. In return, the standard gives exact complexity bounds, often as a count of comparisons or assignments rather than a big-O estimate.

> **Mental model.** An algorithm is a loop with a contract. It moves and compares elements inside the range you name, it returns an iterator to tell you where the interesting part ends, and it trusts every precondition without checking it.

## Ranges, iterators and callables

A range is half-open, `[first, last)`: `first` is included and `last` is not, so an empty range is `first == last` and the number of elements is `last - first`. Algorithms return iterators in the same convention, which is why "not found" is reported by returning `last`.

The names of template parameters carry requirements. A parameter called `InputIterator` must meet the input-iterator requirements, `ForwardIterator` must be multi-pass, and so on. `std::sort` asks for `RandomAccessIterator`, which a `std::list` iterator is not, so `std::sort(l.begin(), l.end())` violates the requirement; in practice it fails to compile deep inside the implementation, where it tries to subtract two list iterators. That is why `std::list` has its own `sort` member.

Function objects come with two rules from [algorithms.requirements] that matter in practice:

- A predicate must not modify elements through the iterator it is given, and calling it on a `const` view of the same element must give the same answer.
- Unless an algorithm says otherwise, it may copy function objects freely. A predicate that keeps state in itself may see that state split across copies.

```cpp
#include <vector>
#include <algorithm>

void demo() {
  std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9};
  auto third = [n = 0](int) mutable { return ++n == 3; };
  // Not guaranteed to remove only the third element.
  // libstdc++ removes 3 and 6 (the predicate is copied after a find_if);
  // libc++ removes only 3.
  v.erase(std::remove_if(v.begin(), v.end(), third), v.end());
}
```

If you need shared state, keep it outside the function object and capture it by reference, or wrap the object in `std::ref`. `std::for_each` is the exception that returns its function object, so it can be used to accumulate.

## What `remove` and `unique` actually do

`std::remove(first, last, value)` shifts the elements to keep towards the front, preserving their order, and returns an iterator to the new logical end. The physical size of the container does not change. The elements in `[result, last)` are in a valid but unspecified state, because the algorithm may have moved from them; for `int` they usually still hold old values, for `std::string` they may be empty.

```cpp
#include <algorithm>
#include <vector>

void demo() {
  std::vector<int> v{1, 2, 3, 2, 5};
  auto it = std::remove(v.begin(), v.end(), 2);
  // v.size() is still 5, it - v.begin() is 3, v starts with 1 3 5
  v.erase(it, v.end());   // the erase-remove idiom: now v.size() is 3
}
```

Since C++20, `std::erase(v, value)` and `std::erase_if(v, pred)` do both steps for `vector`, `deque`, `basic_string`, `list` and `forward_list`; for the two lists they use the efficient member functions.

`std::unique` follows the same pattern but only collapses **adjacent** equal elements. `{1, 1, 2, 1, 1}` becomes `{1, 2, 1}` after erase-unique, not `{1, 2}`. To remove all duplicates, sort first. `remove`, `remove_if` and `unique` are stable: the kept elements stay in their original order.

> **Standardese.** [alg.remove] states that each element in `[ret, last)` has a valid but unspecified state, and it calls the algorithms stable. [alg.unique] requires the comparison to be an equivalence relation, and the result keeps only the first element of each group of consecutive equivalent elements.

## Copying, overlap and in-place transforms

`std::copy(first, last, d_first)` assigns forward, from `first` towards `last`. Its precondition is that `d_first` is not in `[first, last)`. Copying a range onto an overlapping destination that starts inside the source is undefined behavior: a forward loop would overwrite elements before reading them, and an implementation is free to use `memmove`, a vectorised loop, or anything else.

When the destination overlaps the source on the right, use `std::copy_backward`, which takes the end of the destination and assigns from the back. Its precondition is the mirror image: `d_last` must not be in `(first, last]`. `std::move` and `std::move_backward` follow the same rules.

```cpp
#include <algorithm>
#include <vector>

void demo() {
  std::vector<int> v{1, 2, 3, 4, 5};
  // std::copy(v.begin(), v.begin() + 3, v.begin() + 1);   // UB: overlap
  std::copy_backward(v.begin(), v.begin() + 3, v.begin() + 4);
  // v is now 1 1 2 3 5
}
```

`std::transform` is different: its specification explicitly allows the output to equal the input, so `std::transform(v.begin(), v.end(), v.begin(), f)` is a well-defined in-place update. Partial overlap is still not allowed.

## Sorting and sorted-range algorithms

`std::sort` is unstable: equivalent elements may be reordered. Since C++11 it guarantees *O*(*N* log *N*) comparisons in the worst case; C++03 only promised that on average. `std::stable_sort` keeps equivalent elements in order and performs *O*(*N* log *N*) comparisons if it can allocate a buffer, and *O*(*N* log² *N*) otherwise. `std::partial_sort` sorts only a prefix, and `std::nth_element` puts one element in its sorted position with smaller ones before it, in linear time on average.

All of these need a comparator that is a strict weak ordering. What that means and what breaks without it belongs to its own topic; the short version is that `<=` is not one, and using it is undefined behavior.

The binary-search family, `lower_bound`, `upper_bound`, `equal_range` and `binary_search`, does not actually require a sorted range. It requires the range to be **partitioned** with respect to the value being searched: all elements for which `e < value` come before all others. A sorted range satisfies this for every value, but an unsorted one may satisfy it for some.

```cpp
#include <algorithm>
#include <vector>

std::vector<int> v{3, 1, 2, 5, 9, 7};      // not sorted
auto it = std::lower_bound(v.begin(), v.end(), 5);
// well-defined: {3,1,2} are < 5 and {5,9,7} are not; it - v.begin() is 3
```

When the precondition is violated, the result is not merely a wrong answer that the standard specifies; it is a precondition violation with undefined behavior. In practice you get an arbitrary iterator. `lower_bound` performs about log₂(*N*) comparisons, plus a constant, for any forward iterator, but advancing a forward iterator is linear, so on a `std::list` it saves comparisons, not steps.

The same goes for `merge`, `includes`, `set_union`, `set_intersection` and `set_difference`: they all expect input sorted by the comparator you pass them.

> **Pitfall.** Sorting with one comparator and searching with another is a silent precondition violation. If you sort by `name` and then call `lower_bound` comparing by `id`, the range is not partitioned with respect to the search and the result is meaningless.

## Partitions and heaps

`std::partition` reorders a range so that elements satisfying a predicate come first, and returns the boundary. It is unstable and uses linear predicate applications; `std::stable_partition` preserves order, at the cost of a buffer or *O*(*N* log *N*) swaps. `std::partition_point` finds the boundary of an already partitioned range by binary search, which is what the binary-search family does internally.

The heap algorithms maintain a binary max-heap inside a random-access range, the structure `std::priority_queue` is built on.

```cpp
#include <algorithm>
#include <vector>

void demo() {
  std::vector<int> v{3, 1, 4, 1, 5, 9, 2, 6};
  std::make_heap(v.begin(), v.end());   // v.front() is 9, the largest
  std::pop_heap(v.begin(), v.end());    // moves 9 to v.back(), re-heaps the rest
  v.pop_back();                         // the container removes it
}
```

`make_heap` uses at most 3*N* comparisons, `push_heap` and `pop_heap` logarithmic. Like `remove`, `pop_heap` cannot change the container's size; it only moves the top element to the end.

## The `std::ranges` versions

C++20 added constrained versions in `std::ranges` for almost every algorithm. They differ in four ways.

1. **Concepts.** Requirements are checked with concepts such as `std::sortable` and `std::indirect_unary_predicate`, so passing a `std::list` to `std::ranges::sort` fails at the call with a readable diagnostic.
2. **Ranges and sentinels.** They accept a whole range, or an iterator and a sentinel of a different type, such as a null terminator or an unbounded count.
3. **Projections.** An extra callable is applied to each element before the predicate or comparator sees it, so `std::ranges::sort(people, {}, &Person::age)` sorts by age with the default `std::ranges::less`.
4. **Return types.** They return what they computed instead of discarding it: `ranges::copy` returns an `in_out_result` holding both end iterators, `ranges::remove` returns a `subrange` of the leftover tail, and `ranges::sort` returns the end iterator.

```cpp
#include <algorithm>
#include <string>
#include <vector>

struct Person { std::string name; int age; };

void tidy(std::vector<Person>& ps) {
  std::ranges::sort(ps, {}, &Person::age);
  auto tail = std::ranges::remove(ps, 0, &Person::age);  // subrange to erase
  ps.erase(tail.begin(), tail.end());
}
```

These are function objects, not function templates, so argument-dependent lookup never finds them and you cannot pass explicit template arguments; the topic on customization points and niebloids covers why. When a ranges algorithm is called on an rvalue range whose iterators would dangle, it returns `std::ranges::dangling` instead, which is the subject of the topic on borrowed ranges.

The legacy algorithms still have one thing the ranges versions in C++23 lack: overloads taking an execution policy for parallel execution.

## What to remember

- Algorithms see iterators, not containers, so they never change a container's size.
- Requirements on iterators, predicates and input order are preconditions; violating them is undefined behavior.
- Function objects may be copied freely; keep mutable state outside them.
- `remove` and `unique` return the new logical end; erase the tail, or use C++20 `std::erase_if`. The tail is valid but unspecified.
- `unique` only collapses adjacent duplicates.
- `copy` forbids a destination starting inside the source; use `copy_backward` for overlap to the right. `transform` may write in place.
- `sort` is unstable with worst-case *O*(*N* log *N*) since C++11; `stable_sort` keeps equivalent elements in order.
- Binary searches need the range partitioned with respect to the value, under the same comparator.
- `ranges::` algorithms add concepts, sentinels, projections and informative return types, and are not found by ADL.

## Concept Map Outline

- **The algorithm library:** Loops with contracts over half-open iterator ranges; every requirement is a precondition.
  - **Contract basics:** Algorithms see iterators, never containers, so they cannot change a container's size.
    - **Half-open ranges:** [first, last) includes first, excludes last; not found is reported as last.
    - **Parameter names:** ForwardIterator or RandomAccessIterator in a signature states the required category.
    - **Predicates may be copied:** Function objects can be copied freely, so state inside them may split across copies.
    - **No modifying predicates:** A predicate must not modify elements through the iterator it is given.
  - **remove and unique:** Shift kept elements forward and return the new logical end.
    - **Erase-remove idiom:** Call erase(result, end); C++20 std::erase_if does both steps.
    - **Tail state:** Elements past the returned iterator are valid but unspecified.
    - **Adjacent only:** unique collapses runs of equal neighbours; sort first to remove all duplicates.
  - **Copy and overlap:** Overlap rules are preconditions; breaking them is undefined behavior.
    - **copy:** Destination start must not lie in [first, last).
    - **copy_backward:** For overlap to the right; d_last must not lie in (first, last].
    - **transform in place:** Output may equal an input iterator exactly, by explicit remark.
  - **Sorting and searching:** All need a strict weak ordering; searches need correctly ordered input.
    - **sort:** Unstable, worst-case O(N log N) comparisons since C++11.
    - **stable_sort:** Keeps equivalent elements in order; N log squared N without a buffer.
    - **Binary searches:** Need the range partitioned with respect to the value, not fully sorted.
    - **Same comparator:** Searching with a different ordering than the sort violates the precondition.
  - **Partitions and heaps:** Linear-time reordering and the max-heap behind priority_queue.
    - **partition:** Unstable; stable_partition keeps order at the cost of memory or N log N swaps.
    - **partition_point:** Binary search for the boundary of an already partitioned range.
    - **pop_heap:** Moves the largest element to the back; the container must still pop it.
  - **ranges:: versions:** Constrained function objects added in C++20.
    - **Concept checks:** ranges::sort on a list fails at the call, not deep inside the library.
    - **Projections:** A callable applied to each element first, such as &Person::age.
    - **Return types:** copy gives in_out_result, remove gives a subrange, sort gives the end.
    - **Not found by ADL:** They are objects, so no ADL and no explicit template arguments.

## Standardese Quiz Questions

### Question 1 [warmup] ([alg.remove])

What does this program print?

```cpp
#include <algorithm>
#include <cstdio>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3, 2, 5};
  auto it = std::remove(v.begin(), v.end(), 2);
  std::printf("%zu %td\n", v.size(), it - v.begin());
}
```

A. `3 3`
B. `5 3`
C. `5 5`
D. `3 5`

**Answer (B):** `5 3`

**Why:** `std::remove` only sees iterators, so it cannot change the vector's size. It moves the three kept elements, `1 3 5`, to the front and returns an iterator to the new logical end, three elements in. The size stays 5 until you call `v.erase(it, v.end())`, which is the erase-remove idiom; `3 3` is what you get after that call.

### Question 2 [warmup] ([alg.unique])

What does this program print?

```cpp
#include <algorithm>
#include <cstdio>
#include <vector>

int main() {
  std::vector<int> v{1, 1, 2, 1, 1};
  v.erase(std::unique(v.begin(), v.end()), v.end());
  std::printf("%zu\n", v.size());
}
```

A. `2`
B. `5`
C. `1`
D. `3`

**Answer (D):** `3`

**Why:** `std::unique` removes all but the first element of each run of consecutive equal elements. The runs are `1 1`, `2` and `1 1`, so the result is `1 2 1`, of size 3. Removing every duplicate, giving `2`, would require sorting first, because `unique` never compares elements that are not adjacent.

### Question 3 [warmup] ([alg.sort], [sort], [list.ops])

Which call fails to compile?

```cpp
#include <algorithm>
#include <deque>
#include <list>
#include <vector>

void f(std::vector<int>& v, std::list<int>& l, std::deque<int>& d) {
  std::sort(v.begin(), v.end());         // A
  l.sort();                              // B
  std::ranges::sort(l);                  // C
  std::stable_sort(d.begin(), d.end());  // D
}
```

A. A
B. B
C. C
D. D

**Answer (C):** C

**Why:** `std::ranges::sort` requires a `random_access_range` whose iterators are `std::sortable`, and a list iterator is only bidirectional, so the constraint fails and the call does not compile. The member `list::sort` exists precisely because the generic algorithm cannot handle lists. `deque` iterators are random-access, so `std::stable_sort` on a deque is fine.

### Question 4 [tricky] ([algorithms.requirements], [alg.remove])

What does the C++23 standard guarantee about which elements this removes?

```cpp
#include <algorithm>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9};
  auto third = [n = 0](int) mutable { return ++n == 3; };
  v.erase(std::remove_if(v.begin(), v.end(), third), v.end());
}
```

A. Exactly the third element, `3`
B. The elements `3` and `6`
C. Nothing specific: the algorithm may copy the predicate, so the count can restart in a copy
D. Nothing: the program is ill-formed because the predicate is not `const`-callable

**Answer (C):** Nothing specific: the algorithm may copy the predicate, so the count can restart in a copy

**Why:** [algorithms.requirements] lets algorithms copy function objects freely unless stated otherwise, and the counter lives inside the lambda. libstdc++ passes a copy to an internal `find_if`, which counts to 3, and then continues with the original whose count starts again, so it removes `3` and `6`; libc++ removes only `3`. Both are conforming, so neither concrete answer is guaranteed. Keep the counter outside the lambda and capture it by reference if you need it.

### Question 5 [tricky] ([alg.copy], [res.on.required])

What is the result of this call?

```cpp
#include <algorithm>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3, 4, 5};
  std::copy(v.begin(), v.begin() + 3, v.begin() + 1);
}
```

A. `v` becomes `1 1 2 3 5`
B. `v` becomes `1 1 1 1 5`
C. Undefined behavior
D. Ill-formed: source and destination must be different containers

**Answer (C):** Undefined behavior

**Why:** `std::copy` has the precondition that the destination start is not in `[first, last)`, and `v.begin() + 1` is. Violating a precondition is undefined behavior, so neither the naive forward-loop result `1 1 1 1` nor the `memmove`-like result `1 1 2 3` is promised. Compilers accept the call, since overlap is a run-time property. `std::copy_backward(v.begin(), v.begin() + 3, v.begin() + 4)` is the correct call and gives `1 1 2 3 5`.

### Question 6 [tricky] ([lower.bound], [alg.binary.search.general])

What does this program print?

```cpp
#include <algorithm>
#include <cstdio>
#include <vector>

int main() {
  std::vector<int> v{3, 1, 2, 5, 9, 7};
  auto it = std::lower_bound(v.begin(), v.end(), 5);
  std::printf("%td\n", it - v.begin());
}
```

A. Undefined behavior, because `v` is not sorted
B. `3`
C. `6`
D. `0`

**Answer (B):** `3`

**Why:** `lower_bound` does not require a sorted range, only one partitioned with respect to `e < 5`: every element for which that is true must come before every element for which it is false. Here `3 1 2` are less than 5 and `5 9 7` are not, so the precondition holds and the result is the first element not less than 5, at index 3. Searching for 4 or 8 in the same vector would violate the precondition.

### Question 7 [standardese] ([alg.remove], [defns.valid])

After `auto r = std::remove(v.begin(), v.end(), x);` on a `std::vector<std::string>`, what does the standard say about the elements in `[r, v.end())`?

A. They are copies of the removed elements, in their original order
B. They have a valid but unspecified state
C. Accessing them is undefined behavior
D. They are value-initialized, so each is an empty string

**Answer (B):** They have a valid but unspecified state

**Why:** [alg.remove] notes that each element in the leftover tail has a valid but unspecified state, because the algorithm may have moved from it while shifting kept elements forward. They are still live objects, so destroying, assigning or even reading them is fine; you just cannot rely on their values. They are not reset to empty and need not hold the removed values.

### Question 8 [standardese] ([alg.transform], [alg.copy])

Is this call well-defined?

```cpp
#include <algorithm>
#include <vector>

void scale(std::vector<int>& v) {
  std::transform(v.begin(), v.end(), v.begin(), [](int x) { return x * 10; });
}
```

A. Yes: `transform` explicitly allows the output to be the same as an input
B. No: like `std::copy`, the destination must not lie within the source range
C. Only if `v.size()` is at most one
D. Unspecified: it depends on whether the implementation vectorises

**Answer (A):** Yes: `transform` explicitly allows the output to be the same as an input

**Why:** [alg.transform] has a remark that the result iterator may equal the first or second input iterator, so an exact in-place transform is allowed. `std::copy` has no such remark and forbids a destination start inside the source, which is why the second option is tempting. Partial overlap, such as writing to `v.begin() + 1`, is still not permitted for `transform`.

# Ranges, views, and niebloids

> How C++20 ranges decouple sentinels from iterators, compose lazy views, prevent dangling iterators with borrowed_range, and suppress ADL with niebloids.

- **Source:** C++ Atlas (https://cppatlas.com/topics/ranges-views-and-niebloids)
- **Track:** Iterators, algorithms and ranges
- **Estimated reading time:** 11 minutes
- **ISO C++ clauses:** [ranges.syn] (https://eel.is/c++draft/ranges.syn), [range.range] (https://eel.is/c++draft/range.range), [range.view] (https://eel.is/c++draft/range.view), [range.dangling] (https://eel.is/c++draft/range.dangling), [range.adaptor.object] (https://eel.is/c++draft/range.adaptor.object)
- **cppreference links:** [Ranges library](https://en.cppreference.com/w/cpp/ranges), [std::ranges::range](https://en.cppreference.com/w/cpp/ranges/range), [std::ranges::view](https://en.cppreference.com/w/cpp/ranges/view), [std::ranges::borrowed_range](https://en.cppreference.com/w/cpp/ranges/borrowed_range), [std::ranges::dangling](https://en.cppreference.com/w/cpp/ranges/dangling), [Customization point object](https://en.cppreference.com/w/cpp/ranges/cpo), [std::ranges::to](https://en.cppreference.com/w/cpp/ranges/to)
- **Prerequisites:** name-lookup-and-adl, sfinae-and-concepts

Classical STL algorithms accept two iterators of the **same type** `(first, last)`. That design leaks implementation details into call sites (`std::sort(v.begin(), v.end())`), forbids passing two mismatched iterator types easily, and forces eager intermediate containers whenever you filter or transform elements step by step.

C++20 Ranges rebuilds algorithms around three ideas: **iterator-sentinel pairs**, **lazy non-owning views**, and **ADL-safe invocation rules** via customization point objects and niebloids.

> **Mental model.** A view does not hold elements or run loops on construction; it stores a small handle to an upstream range plus a rule for advancing an iterator. Computation happens element by element only when you pull from the resulting iterator.

## Ranges, sentinels, and views

Under `[range.range]`, a type `R` satisfies `std::ranges::range` when `std::ranges::begin(r)` yields an `input_or_output_iterator` and `std::ranges::end(r)` yields a `sentinel_for<iterator_t<R>>`. Because the sentinel type `S` need not match the iterator type `I`, loops terminate on abstract conditions—such as reaching `'\0'`, exhausting a finite count (`std::default_sentinel_t`), or never terminating (`std::unreachable_sentinel_t`)—without fabricating dummy end iterators.

A `std::ranges::view` refines `range` by opting into `std::ranges::enable_view<T>` and promising **O(1) move construction, move assignment, and destruction** independent of element count. After defect report P2325R3, `view` no longer requires `default_initializable`—allowing closures with captureless or capturing non-default-constructible lambdas to model `view`.

When you pipe a range into `std::views::all(r)`:

- If `r` is already a `view`, it is forwarded directly.
- If `r` is a non-view lvalue container (`std::vector`), `views::all` wraps it in `std::ranges::ref_view`, a non-owning pointer-like wrapper.
- If `r` is a non-view rvalue (`make_vec()`), `views::all` wraps it in `std::ranges::owning_view`, moving ownership of the temporary container into the pipeline object itself.

```cpp
#include <ranges>
#include <vector>

std::vector<int> make_scores() { return {40, 85, 92, 60}; }

void inspect_const_and_ownership() {
    std::vector<int> scores{40, 85, 92, 60};
    auto high = scores | std::views::filter([](int s) { return s >= 80; });
    static_assert(std::ranges::range<decltype(high)>);
    static_assert(!std::ranges::range<const decltype(high)>); // begin() caches!

    // Non-view rvalue becomes an owning_view inside the pipeline
    auto top = make_scores() | std::views::transform([](int s) { return s + 5; });
    static_assert(std::ranges::view<decltype(top)>);
}
```

> **Pitfall.** `std::ranges::filter_view` and `drop_while_view` must locate the first matching element in amortized O(1) time, so they **cache the result of `begin()`** inside the view object. Because caching mutates internal state, `begin()` is non-`const`—meaning `const filter_view` does not even satisfy `std::ranges::range`. Accept views by forwarding reference `auto&&` or value, not `const auto&`.

## Borrowed ranges and std::ranges::dangling

What happens if an algorithm returns an iterator into a temporary container that dies at the semicolon?

```cpp
#include <algorithm>
#include <concepts>
#include <ranges>
#include <string_view>
#include <vector>

std::vector<int> fetch_ids() { return {1, 2, 3}; }

void dangling_protection() {
    auto it_bad = std::ranges::find(fetch_ids(), 2);
    static_assert(std::same_as<decltype(it_bad), std::ranges::dangling>);
    // *it_bad; // Compile error: std::ranges::dangling cannot be dereferenced

    auto it_ok = std::ranges::find(std::string_view{"lucid"}, 'c');
    static_assert(!std::same_as<decltype(it_ok), std::ranges::dangling>);
}
```

C++20 solves this at compile time with `std::ranges::borrowed_range<R>`. A range is borrowed if it is an lvalue reference (`R&`) or if `std::ranges::enable_borrowed_range<std::remove_cvref_t<R>>` is `true`—indicating its iterators point to external storage whose lifetime is decoupled from the range wrapper itself (`std::string_view`, `std::span`, `std::ranges::subrange`, `views::iota`).

Algorithms returning iterators into an input range return `std::ranges::borrowed_iterator_t<R>`, which evaluates to `std::ranges::dangling` whenever `R` fails `borrowed_range`. Notice the subtle interaction with `owning_view`: `make_vec() | views::transform(...)` is valid because `owning_view` owns the vector for the lifetime of the view, yet that pipeline is **not** a `borrowed_range`, so calling `std::ranges::find` on the pipeline temporary still safely yields `std::ranges::dangling`.

> **Standardese.** Under `[range.dangling]`, `std::ranges::dangling` is an empty class type constructible from any arguments. Algorithms returning `borrowed_iterator_t<R>` still run and return `dangling` when `R` is a non-borrowed rvalue, allowing callers to ignore the result safely while blocking accidental dereferencing.

## CPOs, niebloids, and pipeable adaptors

Two distinct mechanisms power `std::ranges` syntax, and standardese keeps them sharply separated:

```text
Customization Point Object (std::ranges::begin / swap)
  └─ inline constexpr function object -> dispatches to member / ADL / fallback

Niebloid (std::ranges::sort / find)
  └─ function-like entity inhibiting ADL -> supports projections, blocks rogue ADL overloads
```

A **Customization Point Object (CPO)** such as `std::ranges::begin`, `std::ranges::size`, or `std::ranges::swap` is a `semiregular` `inline constexpr` function object whose `operator()` performs standardized dispatch (for example, checking a member function first, then ADL in a constrained context, then a default implementation). Because it is an object rather than a function template, calling `std::ranges::swap(a, b)` requires no `using std::swap;` boilerplate.

A **niebloid**—the community name for `std::ranges` algorithm entities such as `std::ranges::sort` and `std::ranges::find`—serves the opposite goal: **preventing ADL**. When a caller writes `using std::ranges::find; find(my_vec, 42);`, ordinary unqualified lookup finds a non-function entity (implemented as an `inline constexpr` function object in standard libraries), which inhibits Argument-Dependent Lookup into user namespaces. Unlike classic `std::sort`, niebloids also accept **projections** (`std::ranges::sort(users, {}, &User::id)`) because they are not restricted by function-template overload resolution quirks.

Pipeability (`r | adaptor`) comes from **Range Adaptor Closure Objects**. Calling `std::views::filter(pred)` returns a closure object implementing `operator|`. Since C++23, user types can inherit from `std::ranges::range_adaptor_closure<Derived>` to participate identically in `|` pipelines and compose with standard views (`views::filter(p) | my_closure()`).

## Materializing pipelines with std::ranges::to

Lazy views do not allocate, which leaves one frequent task at the end of a pipeline: materializing results back into an owning container. C++23 adds `std::ranges::to<Container>()`, supporting both direct construction and pipe syntax without manually converting sentinel-bounded views to common ranges first.

```cpp
#include <algorithm>
#include <ranges>
#include <vector>

struct Task { int priority; };

struct take_two_fn : std::ranges::range_adaptor_closure<take_two_fn> {
    template <std::ranges::viewable_range R>
    constexpr auto operator()(R&& r) const {
        return std::views::take(std::forward<R>(r), 2);
    }
};
inline constexpr take_two_fn take_two{};

std::vector<int> top_priorities(std::vector<Task>& tasks) {
    std::ranges::sort(tasks, std::ranges::greater{}, &Task::priority);
    return tasks
        | std::views::transform(&Task::priority)
        | std::views::filter([](int p) { return p > 0; })
        | take_two
        | std::ranges::to<std::vector>();
}
```

| Concept or entity | Core constraint or rule | Owns elements | Safe for rvalue iterators | Typical example |
| --- | --- | --- | --- | --- |
| `std::ranges::range` | `begin(r)` iterator + `end(r)` sentinel | Usually | Only if borrowed | `std::vector<int>` |
| `std::ranges::view` | `range` + `movable` + `enable_view` (`O(1)` move/destroy) | No (except `owning_view`) | No (unless borrowed) | `views::filter`, `views::transform` |
| `borrowed_range` | Lvalue range or `enable_borrowed_range == true` | No | Yes (`borrowed_iterator_t` is real) | `std::string_view`, `std::span`, `subrange` |
| CPO | `inline constexpr` object dispatching member/ADL | N/A | N/A | `std::ranges::begin`, `std::ranges::swap` |
| Niebloid | ADL-inhibiting algorithm entity with projections | N/A | Returns `dangling` if unborrowed | `std::ranges::sort`, `std::ranges::find` |

> **Mental model.** Keep pipelines lazy while filtering, slicing, and projecting; materialize with `std::ranges::to` only at the ownership boundary where results must outlive their source or populate a container.

## What to remember

- Ranges separate iterator and sentinel types, eliminating mismatched-iterator errors and dummy end sentinels.
- Views cache state lazily (`filter_view` caches `begin()`), so `const` views may fail `std::ranges::range`; pass views by value or `auto&&`.
- Non-`borrowed_range` rvalues cause iterator-returning `std::ranges` algorithms to yield `std::ranges::dangling` rather than dangling pointers.
- `views::all` wraps lvalue containers in `ref_view` and non-view rvalues in `owning_view`, letting temporary containers power `|` pipelines safely.
- CPOs enable constrained customization, while niebloids inhibit ADL and support projections; C++23 `range_adaptor_closure` and `ranges::to` complete user pipelines.

## Concept Map Outline

- **Ranges, views, and niebloids:** C++20 ranges replace raw iterator pairs with sentinels, lazy views, lifetime checks, and ADL-safe algorithms.
  - **Iterators and sentinels:** A range pairs begin() with any sentinel type modeling sentinel_for<iterator_t<R>>.
    - **Decoupled end types:** Sentinels represent termination conditions like null bytes without matching iterator types.
    - **ref_view vs owning_view:** views::all borrows lvalues via ref_view and moves non-view rvalues into owning_view.
  - **Lazy views:** Views model movable ranges with O(1) move and destruction, computing elements on demand.
    - **Const iteration caveat:** filter_view caches begin() internally, so const filter_view does not satisfy range.
      - **Pass views by value:** Accept views by forwarding reference or value rather than const reference.
    - **Non-default views:** DR P2325R3 removed default_initializable from std::ranges::view requirements.
  - **Borrowed ranges and dangling:** Algorithms avoid returning dangling iterators from expiring temporary containers.
    - **enable_borrowed_range opt-in:** Types like string_view, span, and subrange opt in because iterators outlive the handle.
    - **std::ranges::dangling:** Non-borrowed rvalues return a compile-checked placeholder that refuses dereferencing.
  - **CPOs and niebloids:** Function objects replace fragile unqualified ADL calls with predictable lookup rules.
    - **Customization point objects:** Inline constexpr objects like ranges::begin dispatch cleanly to member or ADL hooks.
    - **Niebloids inhibit ADL:** Algorithms like ranges::sort block rogue ADL overloads and accept projection arguments.
      - **Built-in projection parameter:** Niebloid algorithms accept a callable or member pointer projection directly.
  - **Pipelines and materialization:** Pipe operators compose closures lazily until collected back into an owning container.
    - **range_adaptor_closure:** C++23 base class lets user adaptors compose seamlessly via operator|.
    - **std::ranges::to:** C++23 converter materializes lazy pipelines directly into owning containers.
      - **Nested container conversion:** std::ranges::to recursively constructs nested containers without common_view adapters.

## Standardese Quiz Questions

### Question 1 [warmup] ([range.filter.view], [range.view])

Why does const std::ranges::filter_view fail to satisfy std::ranges::range?

```cpp
std::vector<int> v{1, 2, 3, 4};
const auto evens = v | std::views::filter([](int x) { return x % 2 == 0; });
```

A. filter_view deletes its const copy constructor
B. filter_view caches the first matching position inside begin() to guarantee O(1) amortized begin(), so begin() must mutate internal state and cannot be const
C. All views in C++20 prohibit const qualification
D. filter_view stores elements inside a mutable std::vector

**Answer (B):** filter_view caches the first matching position inside begin() to guarantee O(1) amortized begin(), so begin() must mutate internal state and cannot be const

**Why:** To satisfy the O(1) amortized begin() requirement of std::ranges::range, filter_view caches the iterator to the first element matching the predicate on its first begin() call. Because that mutates a member cache, filter_view only provides non-const begin().

### Question 2 [warmup] ([range.all], [range.owning.view])

What does std::views::all(make_vec()) produce when given a non-view rvalue std::vector<int>?

```cpp
std::vector<int> make_vec();
auto adapted = std::views::all(make_vec());
```

A. A compilation error because temporary containers cannot become views
B. A std::ranges::ref_view holding a dangling pointer to the temporary vector
C. A std::ranges::dangling placeholder
D. A std::ranges::owning_view<std::vector<int>> that moves and owns the vector inside the view

**Answer (D):** A std::ranges::owning_view<std::vector<int>> that moves and owns the vector inside the view

**Why:** Since P2415R2 (a C++20 DR), std::views::all wraps non-view rvalue ranges in std::ranges::owning_view, moving the temporary container into the view so pipe chains like make_vec() | views::transform(...) stay valid.

### Question 3 [tricky] ([range.dangling], [range.owning.view])

What is the exact return type of std::ranges::find(make_vec() | std::views::transform(fn), 4)?

```cpp
std::vector<int> make_vec();
auto fn = [](int x) { return x * 2; };
auto res = std::ranges::find(make_vec() | std::views::transform(fn), 4);
```

A. std::ranges::dangling, because a transform_view over an owning_view is not a borrowed_range
B. A valid iterator into the moved temporary vector
C. Compilation error inside std::ranges::find because rvalue pipelines are rejected
D. std::nullptr_t

**Answer (A):** std::ranges::dangling, because a transform_view over an owning_view is not a borrowed_range

**Why:** Even though owning_view keeps the temporary vector alive for the duration of the view object, the view itself dies at the semicolon of the find() call and owning_view does not opt into enable_borrowed_range. Hence borrowed_iterator_t<R> resolves to std::ranges::dangling.

### Question 4 [tricky] ([range.range], [string.view.synop])

Why does std::ranges::find(std::string_view{"lucid"}, 'c') return a real iterator instead of std::ranges::dangling, even though the argument is a prvalue?

```cpp
auto it = std::ranges::find(std::string_view{"lucid"}, 'c');
```

A. String literals trigger special compiler exemption inside std::ranges::find
B. std::string_view is a trivial type, and all trivial types return real iterators
C. std::string_view specializes std::ranges::enable_borrowed_range to true because its iterators refer to external storage independent of the view object
D. std::ranges::find takes string_view by const lvalue reference

**Answer (C):** std::string_view specializes std::ranges::enable_borrowed_range to true because its iterators refer to external storage independent of the view object

**Why:** A range R models std::ranges::borrowed_range when it is an lvalue reference or when enable_borrowed_range<remove_cvref_t<R>> is true. std::string_view and std::span opt into enable_borrowed_range so rvalue views still return valid iterators.

### Question 5 [standardese] ([algorithms.requirements], [basic.lookup.argdep])

How do niebloids such as std::ranges::sort differ in lookup behavior from unconstrained function templates like std::sort when brought into scope with a using-declaration?

```cpp
using std::ranges::sort;
sort(user_range);
```

A. Niebloids perform ADL in associated namespaces just like std::sort
B. Niebloids are designated function-like entities that inhibit ADL, so unqualified lookup resolves solely to std::ranges::sort without calling ADL overloads in user namespaces
C. Niebloids invoke member .sort() on the container if present
D. Niebloids require explicit template arguments to suppress ADL

**Answer (B):** Niebloids are designated function-like entities that inhibit ADL, so unqualified lookup resolves solely to std::ranges::sort without calling ADL overloads in user namespaces

**Why:** Under [algorithms.requirements], std::ranges algorithms (niebloids) are not found by ADL and inhibit ADL when found by unqualified lookup (typically implemented as inline constexpr function objects). Unlike CPOs, they intentionally block customization via ADL.

### Question 6 [standardese] ([range.view])

After defect report P2325R3 (applied to C++20), which requirement was removed from the std::ranges::view concept?

A. std::movable<T>
B. std::ranges::range<T>
C. std::default_initializable<T>
D. std::ranges::enable_view<T>

**Answer (C):** std::default_initializable<T>

**Why:** Originally C++20 required std::ranges::view<T> to subsume std::semiregular<T>, which included default_initializable<T>. P2325R3 relaxed view to require movable<T> instead of semiregular<T> so views wrapping non-default-constructible lambdas or references (ref_view) remain valid views.

# Ranges and views

> A range is anything you can call ranges::begin and ranges::end on; a view is a range cheap enough to pass by value and compose lazily. Views compute on demand, may cache, and refer to data they usually do not own, which explains both their power and their sharp edges.

- **Source:** C++ Atlas (https://cppatlas.com/topics/ranges-and-views)
- **Track:** Iterators, algorithms and ranges
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [range.range] (https://eel.is/c++draft/range.range), [range.sized] (https://eel.is/c++draft/range.sized), [range.view] (https://eel.is/c++draft/range.view), [range.refinements] (https://eel.is/c++draft/range.refinements), [range.all] (https://eel.is/c++draft/range.all), [range.ref.view] (https://eel.is/c++draft/range.ref.view), [range.owning.view] (https://eel.is/c++draft/range.owning.view), [range.filter.view] (https://eel.is/c++draft/range.filter.view), [range.utility.conv.to] (https://eel.is/c++draft/range.utility.conv.to), [stmt.ranged] (https://eel.is/c++draft/stmt.ranged)
- **cppreference links:** [Ranges library](https://en.cppreference.com/w/cpp/ranges), [std::ranges::view](https://en.cppreference.com/w/cpp/ranges/view), [std::views::all](https://en.cppreference.com/w/cpp/ranges/all_view), [std::ranges::owning_view](https://en.cppreference.com/w/cpp/ranges/owning_view), [std::ranges::filter_view](https://en.cppreference.com/w/cpp/ranges/filter_view), [std::ranges::to](https://en.cppreference.com/w/cpp/ranges/to)
- **Prerequisites:** iterator-categories-and-concepts, concepts-and-constraints, algorithms

## The one idea

A **range** is an object you can ask for a beginning and an end. A **view** is a range with one extra promise: moving it, destroying it, and copying it if it is copyable are cheap, independent of how many elements it presents. That promise is what lets views be passed by value, stored inside other views, and stacked into pipelines without anyone worrying about cost.

Most views do not hold elements. They hold a way to reach elements, such as a reference to a container plus a function, and they do their work only when you iterate.

> **Mental model.** A container is a warehouse. A view is a set of directions to the warehouse, with instructions for what to do with each item you find. Directions are cheap to copy, they do nothing until followed, and they lead nowhere once the warehouse is gone.

## The range concept family

`std::ranges::range<R>` requires that `std::ranges::begin` and `std::ranges::end` work on an lvalue of type `R`. The two may return different types: the end is a **sentinel**, which only has to be comparable with the iterator. Semantically, both calls must be amortized constant time, which matters for the caching discussed below.

Refinements add one property each:

| Concept | Adds |
| --- | --- |
| `input_range` through `contiguous_range` | the iterator models the matching iterator concept |
| `sized_range` | `ranges::size(r)` works in amortized constant time |
| `common_range` | iterator and sentinel have the same type |
| `borrowed_range` | iterators stay valid after the range object dies |
| `view` | cheap move and destruction, opted in through `enable_view` |
| `viewable_range` | can be safely converted to a view with `views::all` |
| `constant_range` (C++23) | elements cannot be modified through the iterators |

The associated types follow the iterator ones: `std::ranges::iterator_t<R>`, `sentinel_t<R>`, `range_value_t<R>`, `range_reference_t<R>`, and `range_size_t<R>`.

Not every view is sized or common. `views::iota(0)` has no end value, so its sentinel is a distinct type and it is not common. `views::filter` cannot know how many elements pass without looking, so `ranges::size` on it does not compile.

## What makes a view

The `view` concept is `range<T> && movable<T> && enable_view<T>`. The syntactic part is cheap; the meaning lives in the semantic requirements. A type models `view` only if move construction is constant time, copy construction, when available, is constant time, copy assignment costs no more than destroying and copy-constructing, and destroying N copies or moved-from copies of a view over M elements costs O(N + M).

Opting in is done by deriving from `std::ranges::view_interface<D>`, which also supplies `empty()`, `front()`, `operator[]` and similar helpers, or from `std::ranges::view_base`, or by specializing `enable_view`. The standard specializes it for `std::string_view` and `std::span`. A `std::vector` is a range but not a view, because copying it copies every element.

```cpp
#include <ranges>
#include <span>
#include <string_view>
#include <vector>

static_assert(std::ranges::view<std::string_view>);
static_assert(std::ranges::view<std::span<int>>);
static_assert(!std::ranges::view<std::vector<int>>);   // copying is O(n)
```

The rules were loosened after C++20 shipped, by papers applied as defect reports to C++20 itself. P2325R3 removed the requirement that views be default-constructible. P2415R2 replaced "destruction is constant time" with the O(N + M) rule above, which allows a view to own its elements as long as it cannot be copied. That made `std::ranges::owning_view` possible: a move-only view that holds a container by value.

> **Standardese.** [range.view] states the complexity requirements as semantic constraints. A type can satisfy `view` syntactically and still fail to model it. By [res.on.requirements], a program that relies on a concept being modeled when it is only satisfied is ill-formed, no diagnostic required, so the compiler will not save you.

## `views::all`, `ref_view` and `owning_view`

Every range adaptor starts by turning its input into a view with `views::all`. The rule has three steps:

1. If the argument, decayed, is already a view, copy or move it.
2. Otherwise, if it is an lvalue, wrap it in `std::ranges::ref_view`, which stores a pointer to the range.
3. Otherwise, it is an rvalue container, so move it into an `std::ranges::owning_view`.

```cpp
#include <ranges>
#include <string_view>
#include <type_traits>
#include <vector>

std::vector<int> v{1, 2, 3};
using A = decltype(std::views::all(v));
using B = decltype(std::views::all(std::vector<int>{}));
using C = decltype(std::views::all(std::string_view{}));

static_assert(std::is_same_v<A, std::ranges::ref_view<std::vector<int>>>);
static_assert(std::is_same_v<B, std::ranges::owning_view<std::vector<int>>>);
static_assert(std::is_same_v<C, std::string_view>);
```

This is the meaning of `viewable_range`: a range that `views::all` accepts. Before P2415, step three did not exist, and piping a temporary vector into an adaptor was ill-formed. The lifetime consequences of all three cases belong to the topic on borrowed ranges and dangling.

## Lazy evaluation

Building a pipeline evaluates nothing. Each dereference of a `views::transform` iterator calls the function again, and a `views::filter` iterator evaluates its predicate as it advances. Iterating the same view twice repeats the work.

The combination of the two is a classic surprise. With `transform` before `filter`, the filter's predicate dereferences the underlying transform iterator, and then your loop dereferences it again, so every element that passes is transformed twice.

```cpp
#include <cstdio>
#include <ranges>
#include <vector>

int calls = 0;

void demo() {
  std::vector<int> v{1, 2, 3, 4};
  auto r = v | std::views::transform([](int x) { ++calls; return x; })
             | std::views::filter([](int x) { return x % 2 == 0; });
  for (int x : r) (void)x;
  std::printf("%d\n", calls);   // 6: four predicate checks, two loop derefs
}
```

If the transformation is expensive, put the filter first, or materialize the transformed values once.

## Const iteration and caching

The `range` concept requires `begin()` to be amortized constant time. `filter_view` cannot find its first matching element in constant time, so it finds it once, caches the iterator inside the view, and returns the cached value from then on. `drop_while_view` does the same, and so does `drop_view` over a range that is not random-access and sized.

Caching mutates the view, so these views provide only a non-`const` `begin()`. A `const filter_view` is not a range at all.

```cpp
#include <ranges>
#include <vector>

void show(const auto& r) {
  for (int x : r) (void)x;
}

void demo(std::vector<int>& v) {
  auto evens = v | std::views::filter([](int x) { return x % 2 == 0; });
  // show(evens);   // ill-formed: filter_view has no const begin()
  for (int x : evens) (void)x;   // fine on a non-const view
}
```

Generic functions that accept views should therefore take them by value or by forwarding reference, not by `const&`. Two consequences of the cache are easy to miss. First, iterating a filtered view a second time skips the search for the first element, so a predicate with side effects runs fewer times on the second pass. Second, the cache is a stored iterator into the underlying range. If you insert into the vector after the first iteration, reallocation invalidates the cached iterator, and iterating the view again is undefined behavior.

> **Pitfall.** A view never sees operations on the range it refers to. Any container operation that invalidates iterators also invalidates the iterators inside a view of that container, including cached ones, so rebuild the view after modifying the container.

`filter_view` adds one more rule: you may modify elements through its iterators, but if an element no longer satisfies the predicate, the behaviour is undefined, because the view's invariant is broken.

## `ranges::to` and range-based `for`

Views produce elements but do not store them. C++23 adds `std::ranges::to` to materialize any range into a container. Given a class template, it deduces the element type; given a complete type, it converts each element.

```cpp
#include <list>
#include <ranges>
#include <vector>

void demo() {
  auto v = std::views::iota(1, 4) | std::ranges::to<std::vector>();  // std::vector<int>
  auto l = v | std::views::filter([](int x) { return x > 1; })
             | std::ranges::to<std::list<long>>();                   // 2, 3 as long
}
```

`ranges::to` tries, in order, direct construction from the range, a constructor taking the `std::from_range` tag, a constructor taking an iterator pair, and finally default construction followed by appending each element.

Range-based `for` predates ranges and does not use `std::ranges::begin`. It binds the range to `auto&& __range`, and calls member `begin()` and `end()` if the class has both, or otherwise unqualified `begin` and `end` found by argument-dependent lookup. Since C++17 the two results may have different types, which is what lets a non-common view be used in a loop. Because `__range` is a non-`const` reference to the view, a filtered view works in a loop even though it is not const-iterable.

## What to remember

- A range needs `ranges::begin` and `ranges::end`; the end can be a sentinel of a different type.
- A view is a range with constant-time move and destruction proportional to its elements, opted in through `enable_view`.
- `std::vector` is not a view; `std::string_view`, `std::span` and adaptor results are.
- C++20 defect reports dropped default construction (P2325) and allowed move-only owning views (P2415).
- `views::all` passes views through, wraps lvalues in `ref_view`, and moves rvalues into `owning_view`.
- Views are lazy and recompute on every pass; `transform` before `filter` calls the function twice per kept element.
- `filter_view` and other caching views are not const-iterable; take views by value or `auto&&`.
- Modifying the underlying container can invalidate a view's cached iterators.
- C++23 `ranges::to` turns a range into a container.

## Concept Map Outline

- **Ranges and views:** A range has begin and end; a view is a range cheap to move and destroy, composed lazily.
  - **Range concepts:** range needs ranges::begin and ranges::end in amortized constant time.
    - **Sentinels:** The end may have a different type from the iterator; common_range means they match.
    - **sized_range:** ranges::size in amortized O(1); filter_view is not sized.
    - **viewable_range:** A range that views::all can safely turn into a view.
    - **constant_range:** C++23: elements cannot be modified through the range's iterators.
  - **What makes a view:** range, movable and enable_view, plus semantic complexity rules.
    - **Cheap operations:** O(1) move, O(1) copy if copyable, destruction O(N+M) over N copies.
    - **Opting in:** Derive from view_interface or view_base, or specialize enable_view.
    - **C++20 defect reports:** P2325 dropped default construction; P2415 allowed move-only owning views.
    - **Not a view:** std::vector is a range but copying it is O(n), so enable_view is false.
  - **views::all:** Every adaptor converts its input with views::all first.
    - **Views pass through:** An argument that is already a view is copied or moved.
    - **ref_view:** Lvalue ranges are wrapped by pointer; the container must outlive the view.
    - **owning_view:** Rvalue containers are moved in; the result is move-only.
  - **Lazy evaluation:** Building a pipeline computes nothing; work happens on iteration.
    - **Recomputed each pass:** transform calls its function on every dereference, every time.
    - **transform then filter:** Kept elements are transformed twice: once by the predicate, once by the loop.
  - **Caching and const:** Views that cannot find begin in O(1) compute it once and store it.
    - **Not const-iterable:** filter, drop_while and some drop views lack a const begin().
    - **Take by value:** Generic code should accept views by value or auto&&, not const&.
    - **Stale caches:** Container operations that invalidate iterators also invalidate cached ones.
    - **filter invariant:** Writing a value that fails the predicate through filter_view is UB.
  - **Materializing and looping:** Views store no elements; containers and loops consume them.
    - **ranges::to:** C++23: builds a container, deducing the element type from a template.
    - **Range-based for:** Uses member or ADL begin and end, not ranges::begin; types may differ since C++17.

## Standardese Quiz Questions

### Question 1 [warmup] ([range.view], [range.ref.view])

In C++23, which of these `static_assert`s fails?

```cpp
#include <ranges>
#include <span>
#include <string_view>
#include <vector>

static_assert(std::ranges::view<std::string_view>);                        // A
static_assert(std::ranges::view<std::span<int>>);                          // B
static_assert(std::ranges::view<std::vector<int>>);                        // C
static_assert(std::ranges::view<std::ranges::ref_view<std::vector<int>>>); // D
```

A. A
B. B
C. D
D. C

**Answer (D):** C

**Why:** A `static_assert` on a false condition makes the program ill-formed, so line C fails to compile. A view must be cheap to copy if it is copyable, and copying a `std::vector` copies every element, so `enable_view<std::vector<int>>` is `false`. The standard specializes `enable_view` for `basic_string_view` and `span`, and `ref_view` derives from `view_interface`, which opts it in. `ref_view` is a view because it only stores a pointer to the vector.

### Question 2 [warmup] ([range.transform.view])

What does this program print?

```cpp
#include <cstdio>
#include <ranges>
#include <vector>

int calls = 0;

int main() {
  std::vector<int> v{1, 2, 3, 4};
  auto r = v | std::views::transform([](int x) { ++calls; return x * x; });
  std::printf("%d ", calls);
  int y = r[2];
  std::printf("%d %d\n", calls, y);
}
```

A. `0 1 9`
B. `4 4 9`
C. `4 5 9`
D. `0 4 9`

**Answer (A):** `0 1 9`

**Why:** Building a view evaluates nothing: `r` stores a `ref_view` of `v` and the lambda, so `calls` is still 0. `r[2]` advances the iterator by 2, which does not call the function, and then dereferences once, so exactly one call computes `3 * 3`. The tempting `4` answers assume the adaptor transforms the whole vector up front, which is how an eager `std::transform` into a new container behaves.

### Question 3 [warmup] ([range.all.general], [range.owning.view])

In C++23, what is the type of `views::all(std::vector<int>{1, 2})`?

A. `std::ranges::ref_view<std::vector<int>>`
B. `std::ranges::owning_view<std::vector<int>>`
C. `std::vector<int>`
D. It is ill-formed: an rvalue container cannot be turned into a view

**Answer (B):** `std::ranges::owning_view<std::vector<int>>`

**Why:** `views::all` copies an argument that is already a view, wraps an lvalue in `ref_view`, and moves any other rvalue range into an `owning_view`. A `ref_view` of a temporary would dangle immediately, which is why it is not chosen. The ill-formed answer describes C++20 as originally published; P2415R2 added `owning_view` and was applied to C++20 as a defect report.

### Question 4 [tricky] ([range.filter.view], [range.filter.iterator], [range.transform.iterator])

What does this program print?

```cpp
#include <cstdio>
#include <ranges>
#include <vector>

int calls = 0;

int main() {
  std::vector<int> v{1, 2, 3, 4};
  auto r = v | std::views::transform([](int x) { ++calls; return x; })
             | std::views::filter([](int x) { return x % 2 == 0; });
  for (int x : r) (void)x;
  std::printf("%d ", calls);
  calls = 0;
  for (int x : r) (void)x;
  std::printf("%d\n", calls);
}
```

A. `4 4`
B. `6 6`
C. `6 4`
D. `4 2`

**Answer (C):** `6 4`

**Why:** The filter checks each element by dereferencing the transform iterator, which costs four calls, and the loop dereferences each of the two kept elements again, for six. On the second loop, `filter_view::begin()` returns the iterator it cached the first time, so the search that examined `1` and `2` is skipped; the remaining calls are `2` dereferenced in the loop, `3` and `4` checked, and `4` dereferenced, which is four. `6 6` is the answer if you forget the cache.

### Question 5 [tricky] ([range.filter.view], [range.range], [stmt.ranged])

Is this program well-formed?

```cpp
#include <ranges>
#include <vector>

void show(const auto& r) {
  for (int x : r) (void)x;
}

int main() {
  std::vector<int> v{1, 2, 3, 4};
  show(v | std::views::filter([](int x) { return x % 2 == 0; }));
}
```

A. Yes: a `const&` parameter binds to the temporary view
B. Ill-formed: `filter_view` has no `const`-qualified `begin()`
C. Ill-formed: a view cannot bind to a reference parameter
D. Undefined behavior: the view is a temporary

**Answer (B):** Ill-formed: `filter_view` has no `const`-qualified `begin()`

**Why:** `filter_view::begin()` must cache the first matching iterator to meet the amortized constant-time requirement of `range`, so it is a non-`const` member and `const filter_view` does not model `range`. The range-based `for` on `const auto&` therefore finds no usable `begin`. The binding itself is fine, and the temporary lives until the end of the full-expression, so the other answers are wrong; take views by value or by `auto&&`.

### Question 6 [tricky] ([range.prim.size], [range.sized], [range.filter.view])

What happens with `std::ranges::size(f)`?

```cpp
#include <ranges>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3, 4};
  auto f = v | std::views::filter([](int x) { return x > 1; });
  auto n = std::ranges::size(f);
  (void)n;
}
```

A. It returns 3, counting matches in linear time
B. It returns 4, the size of the underlying vector
C. Undefined behavior, because `size` was called before iterating
D. The program is ill-formed: `filter_view` is not a `sized_range`

**Answer (D):** The program is ill-formed: `filter_view` is not a `sized_range`

**Why:** `ranges::size` only works when the size is available in amortized constant time: through a `size()` member or free function, or by subtracting a sized sentinel from the iterator. `filter_view` has neither, because its size depends on how many elements pass the predicate, so the call does not compile. Use `std::ranges::distance(f)`, which is allowed to walk the range and returns 3 here.

### Question 7 [standardese] ([range.filter.iterator])

What does the standard say about this loop?

```cpp
#include <ranges>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3, 4};
  auto evens = v | std::views::filter([](int x) { return x % 2 == 0; });
  for (int& x : evens) x += 1;
}
```

A. It is well-defined; `v` becomes `1 3 3 5`
B. It is ill-formed: `filter_view` iterators are read-only
C. It is undefined behavior, because the modified elements no longer satisfy the predicate
D. It is well-defined, but iterating `evens` again visits no elements

**Answer (C):** It is undefined behavior, because the modified elements no longer satisfy the predicate

**Why:** [range.filter.iterator] permits modifying the element a `filter_view` iterator denotes, but says the behavior is undefined if the new value does not satisfy the predicate. Adding 1 to an even number makes it odd, so the loop breaks the view's invariant. The iterators do yield `int&`, so the code compiles, and observing `1 3 3 5` on a real implementation does not make it defined. Writing a value that stays even would be fine.

### Question 8 [standardese] ([range.view])

Which of these is **not** a requirement of the `std::ranges::view` concept in C++23?

A. The type is `std::movable`
B. Move construction is constant time
C. The type is default-initializable
D. `std::ranges::enable_view<T>` is `true`

**Answer (C):** The type is default-initializable

**Why:** `view<T>` is `range<T> && movable<T> && enable_view<T>`, with semantic requirements that move construction is constant time and that copies and destruction are cheap. C++20 as published also required `default_initializable`, but P2325R3 removed it and was applied to C++20 as a defect report, so a view such as `ref_view` need not have a default constructor. The other three options are all still required.

# Borrowed ranges and dangling

> An iterator is only valid while the thing it points into is alive. Borrowed ranges are the ranges whose iterators survive the range object, and the ranges library uses that property to turn many dangling iterators into compile errors, but views, pipelines and range-based for loops still leave plenty of ways to dangle.

- **Source:** C++ Atlas (https://cppatlas.com/topics/borrowed-ranges-and-dangling)
- **Track:** Iterators, algorithms and ranges
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [range.range] (https://eel.is/c++draft/range.range), [range.dangling] (https://eel.is/c++draft/range.dangling), [range.ref.view] (https://eel.is/c++draft/range.ref.view), [range.owning.view] (https://eel.is/c++draft/range.owning.view), [stmt.ranged] (https://eel.is/c++draft/stmt.ranged), [class.temporary] (https://eel.is/c++draft/class.temporary)
- **cppreference links:** [std::ranges::borrowed_range](https://en.cppreference.com/w/cpp/ranges/borrowed_range), [std::ranges::dangling](https://en.cppreference.com/w/cpp/ranges/dangling), [std::ranges::borrowed_iterator_t](https://en.cppreference.com/w/cpp/ranges/borrowed_iterator_t), [std::ranges::owning_view](https://en.cppreference.com/w/cpp/ranges/owning_view), [Range-based for loop](https://en.cppreference.com/w/cpp/language/range-for)
- **Prerequisites:** ranges-and-views, reference-binding-and-temporaries, object-lifetime-and-storage

## The one idea

Ask a `std::vector` for an iterator and you get a pointer into storage the vector owns. Destroy the vector and the iterator dangles. Ask a `std::string_view` for an iterator and you get a pointer into storage the view merely refers to. Destroy the view and the iterator is still fine, because the characters were never the view's to free.

A range of the second kind is a **borrowed range**: its iterators' validity is not tied to the lifetime of the range object. The ranges library uses this property to decide what an algorithm may safely return when you pass it a temporary.

> **Mental model.** Before keeping an iterator, ask who owns the elements. If the answer is the range object you are about to destroy, the iterator dies with it. If the answer is someone else, the range was only borrowing them, and the iterator lives as long as that someone else.

## `borrowed_range` and opting in

The concept is short:

```cpp
#include <ranges>
#include <type_traits>

template <class R>
concept my_borrowed_range =
    std::ranges::range<R> &&
    (std::is_lvalue_reference_v<R> ||
     std::ranges::enable_borrowed_range<std::remove_cvref_t<R>>);
```

An lvalue reference is always borrowed, because the caller still owns the object after the call. For anything else, the type must opt in by specializing `enable_borrowed_range`, a variable template that is `false` by default. The specialization is a promise you make, not something the compiler checks.

```cpp
#include <ranges>

struct IntSpan {                 // refers to someone else's ints
  int* b; int* e;
  int* begin() const { return b; }
  int* end() const { return e; }
};

template <>
inline constexpr bool std::ranges::enable_borrowed_range<IntSpan> = true;

static_assert(std::ranges::borrowed_range<IntSpan>);
```

> **Standardese.** [range.range] defines `borrowed_range` and says a type models it only if the validity of iterators obtained from an object of that type is not tied to the lifetime of that object. A false specialization of `enable_borrowed_range` satisfies the concept without modeling it, and the program is then ill-formed, no diagnostic required.

## `ranges::dangling`: compile errors instead of crashes

Every `std::ranges` algorithm that returns an iterator into its range argument uses `std::ranges::borrowed_iterator_t<R>` as the return type. That alias is `iterator_t<R>` when `R` is a borrowed range and `std::ranges::dangling` otherwise. Algorithms returning a subrange use `borrowed_subrange_t<R>` in the same way.

`dangling` is an empty struct that can be constructed from anything and does nothing else. It has no `operator*`, no `operator++` and no comparisons, so the moment you try to use the result, the compiler stops you.

```cpp
#include <algorithm>
#include <vector>

std::vector<int> get() { return {3, 1, 2}; }

void demo() {
  auto it = std::ranges::find(get(), 2);   // it is std::ranges::dangling
  // int x = *it;                          // ill-formed: dangling has no operator*
  auto old = std::find(get().begin(), get().end(), 2);
  // compiles, but compares iterators into two different temporaries: UB
  (void)it; (void)old;
}
```

When you do get `dangling`, the fix is almost never to fight the type. Either give the container a name, so that it is passed as an lvalue and outlives the iterator, or, if you only needed a yes-or-no answer, use an algorithm that returns a value, such as `std::ranges::contains` in C++23 or `std::ranges::any_of`. The same applies to subranges: `std::ranges::equal_range(get(), 2)` returns `dangling` where a named vector would give a `subrange` of matching elements.

The protection is only for iterators. Algorithms that return values are unaffected, so `std::ranges::min(get())` returns `1` by value and is perfectly safe. The algorithm also still runs: `dangling` only tells you the result is unusable, it does not skip the work.

## Which standard ranges are borrowed

The standard specializes `enable_borrowed_range` to `true` for:

- `std::basic_string_view` and `std::span`, which refer to elements owned elsewhere;
- `std::ranges::subrange`, which is just an iterator and a sentinel;
- `std::ranges::ref_view`, which holds a pointer to a range that outlives it;
- `std::ranges::empty_view` and `std::ranges::iota_view`, whose iterators carry everything they need, so an `iota_view` iterator holds the current integer itself.

Several adaptors are borrowed exactly when the view they adapt is, because their iterators are just the underlying iterators with a little extra state: `take_view`, `drop_view`, `drop_while_view`, `common_view`, `reverse_view`, `elements_view`, `owning_view`, and in C++23 `adjacent_view` and `zip_view`. `transform_view` and `filter_view` are never borrowed, because their iterators point back into the view object to reach the function or predicate. Containers such as `std::vector` and `std::string` are not borrowed.

```cpp
#include <algorithm>
#include <cstdio>
#include <ranges>
#include <string_view>

void demo() {
  auto a = std::ranges::find(std::string_view("hello"), 'l');  // a real iterator
  auto b = std::ranges::find(std::views::iota(0, 10), 4);      // also fine
  std::printf("%c %d\n", *a, *b);                               // prints l 4
}
```

## Temporaries in views and pipelines

Since P2415, applied to C++20 as a defect report, `views::all` moves an rvalue container into an `owning_view`. A pipeline that starts from a temporary container therefore owns it and cannot dangle.

```cpp
#include <ranges>
#include <vector>

std::vector<int> get();

void demo() {
  auto ok = get() | std::views::filter([](int x) { return x > 1; });
  // ok owns the vector; safe to iterate later
}
```

Owning is not the same as borrowing, though. The view owns the elements, so iterators into it die when the view does; `owning_view` of a vector is not a borrowed range.

The protection disappears when the temporary is hidden behind a reference. If a function returns a reference to a member of a temporary, the pipeline sees an lvalue, wraps it in `ref_view`, and the object behind it is destroyed at the end of the full-expression. The same happens with `std::string_view` built from a temporary `std::string`: `string_view` is borrowed, but only from the string, which is already gone. Clang 21 warns about that one with `-Wdangling-gsl`; neither GCC 16 nor Clang warns about the `take` line.

```cpp
#include <ranges>
#include <string>
#include <string_view>
#include <vector>

struct Holder {
  std::vector<int> v;
  const std::vector<int>& items() const { return v; }
};
Holder make();

void demo() {
  auto bad = make().items() | std::views::take(2);  // ref_view to a dead member
  std::string_view sv = std::string("temporary");   // dangles immediately
  (void)bad; (void)sv;
}
```

## Range-based for and the C++23 lifetime fix

A range-based `for` binds its initializer to `auto&& __range`. Reference binding extends the lifetime of a temporary that is bound directly, so `for (int x : get())` is fine. Before C++23, any other temporary in the initializer was destroyed at the end of that full-expression, before the loop body ran.

```cpp
#include <vector>

struct Holder {
  std::vector<int> v{1, 2, 3};
  const std::vector<int>& items() const { return v; }
};
Holder make() { return {}; }

void demo() {
  for (int x : make().items()) (void)x;
  // C++20: UB, the Holder is destroyed before the first iteration
  // C++23: OK, the Holder lives until the loop ends (P2718)
}
```

The trap is easy to fall into with ordinary-looking accessors. `for (auto& e : load().value())` on a function returning `std::optional<std::vector<T>>`, `for (char c : make_person().name())` with a getter returning `const std::string&`, and `for (auto& kv : config()["section"])` on a temporary map all bind `__range` to something inside a temporary that dies before the first iteration.

C++23 adopted P2718, which extends the lifetime of every temporary created in the for-range-initializer to the end of the loop. GCC 16 and Clang 21 both implement it in `-std=c++23` mode and print the destructor after the loop body; in `-std=c++20` mode they destroy the `Holder` first. The fix applies only to range-based `for`. Writing `auto& r = make().items();` on its own line still dangles in every version.

> **Pitfall.** P2718 is not applied retroactively. Code that relies on it is correct only when compiled as C++23 or later, and the failure in older modes is silent undefined behavior that often appears to work.

## Returning views from functions

A view that refers to a local is a view of a dead object once the function returns. Compilers do not warn about it, because the view type holds a pointer, not a reference.

```cpp
#include <ranges>
#include <vector>

auto evens_bad() {
  std::vector<int> v{1, 2, 3, 4};
  return v | std::views::filter([](int x) { return x % 2 == 0; });  // ref_view: dangles
}

auto evens_ok() {
  std::vector<int> v{1, 2, 3, 4};
  return std::move(v) | std::views::filter([](int x) { return x % 2 == 0; });  // owning_view
}
```

The same reasoning applies to everything a view stores. A lambda passed to `filter` or `transform` is stored by value in the view, but if the lambda captures locals by reference, those references dangle when the function returns. Capture by value instead.

A function that returns a view of its parameter is fine when the parameter is an lvalue reference to the caller's object, and the caller then owns the lifetime question. Taking `const std::vector<int>&` is dangerous because it also binds to temporaries. A forwarding reference passed through `std::views::all(std::forward<R>(r))` handles both cases: lvalues become `ref_view`, rvalues become `owning_view`.

When a function exists to expose part of an object that outlives the call, a return type of `std::span` or `std::string_view` makes the borrowing visible in the signature, so every reader knows to ask who owns the elements. A return type of `auto` hides whether the result owns its data, refers to it, or holds references inside stored lambdas, so it deserves a comment saying which.

## What to remember

- A borrowed range is one whose iterators do not depend on the range object staying alive.
- Lvalue references are always borrowed; other types opt in with `enable_borrowed_range`, unchecked.
- `ranges::` algorithms return `ranges::dangling` for non-borrowed rvalues, which fails at the first use; legacy `std::` algorithms give no such protection.
- `string_view`, `span`, `subrange`, `ref_view`, `empty_view` and `iota_view` are borrowed; `transform_view`, `filter_view` and containers are not.
- A pipeline starting from a temporary container owns it through `owning_view`; a reference to a member of a temporary does not.
- Before C++23, temporaries in a range-for initializer other than the outermost die before the loop; C++23 P2718 keeps them alive.
- Never return a view of a local; move the container in, and capture by value in lambdas stored in views.

## Concept Map Outline

- **Borrowed ranges and dangling:** Iterators are valid only while their elements' owner lives; borrowed ranges do not own them.
  - **borrowed_range:** Iterators obtained from the object stay valid after the object is destroyed.
    - **Lvalue references:** Always borrowed: the caller keeps owning the object.
    - **enable_borrowed_range:** Opt-in variable template, false by default and never checked.
    - **Owning is not borrowed:** owning_view of a vector owns its elements, so it is not borrowed.
  - **ranges::dangling:** Returned instead of an iterator when the range is a non-borrowed rvalue.
    - **borrowed_iterator_t:** iterator_t<R> if R is borrowed, otherwise ranges::dangling.
    - **Fails on use:** dangling has no operator* or ++, so using it is a compile error.
    - **Values are safe:** ranges::min returns a copy, so it works on temporaries.
    - **Legacy std:: unprotected:** std::find on a temporary's iterators compiles and dangles.
  - **Standard borrowed types:** Types whose iterators reach elements owned elsewhere or carry their own state.
    - **Always borrowed:** string_view, span, subrange, ref_view, empty_view and iota_view.
    - **Conditionally borrowed:** take, drop, drop_while, common, reverse, elements: if the base view is.
    - **Never borrowed:** transform_view and filter_view iterators point back into the view.
  - **Pipelines and temporaries:** Ownership follows how views::all sees the argument.
    - **Rvalue container:** Moved into owning_view since P2415, so the pipeline is safe.
    - **Member of a temporary:** Seen as an lvalue, wrapped in ref_view, and dead at the semicolon.
    - **string_view of a temporary:** Borrowed from a string that is destroyed immediately.
  - **Range-based for:** The initializer is bound to auto&& __range for the whole loop.
    - **Before C++23:** Only the temporary bound directly is extended; make().items() dangles.
    - **C++23 P2718:** All temporaries in the for-range-initializer live until the loop ends.
    - **Loop only:** auto& r = make().items(); still dangles in every version.
  - **Returning views:** A view must not outlive what it refers to, including captures.
    - **View of a local:** Returns a ref_view to a destroyed vector; compilers rarely warn.
    - **Move the container in:** return std::move(v) | adaptor gives an owning_view.
    - **Lambda captures:** Capturing locals by reference in a stored lambda dangles on return.

## Standardese Quiz Questions

### Question 1 [warmup] ([range.dangling], [alg.find])

What is the type of `it`?

```cpp
#include <algorithm>
#include <vector>

std::vector<int> get() { return {3, 1, 2}; }

int main() {
  auto it = std::ranges::find(get(), 2);
  (void)it;
}
```

A. `std::vector<int>::iterator`, which dangles at the end of the statement
B. `std::ranges::dangling`
C. `std::ranges::subrange<std::vector<int>::iterator>`
D. The call is ill-formed, because `find` requires an lvalue range

**Answer (B):** `std::ranges::dangling`

**Why:** `ranges::find` returns `borrowed_iterator_t<R>`, and `R` here is `std::vector<int>`, an rvalue of a type that is not a borrowed range. The return type is therefore `std::ranges::dangling`, an empty type with no `operator*`, so the search runs but the compiler rejects any later attempt to dereference or increment `it`. Returning a real vector iterator is what the legacy `std::find` would do, which is the danger this design prevents.

### Question 2 [warmup] ([range.range], [span.overview], [range.owning.view])

Which of these types models `std::ranges::borrowed_range`?

A. `std::vector<int>`
B. `std::string`
C. `std::ranges::owning_view<std::vector<int>>`
D. `std::span<int>`

**Answer (D):** `std::span<int>`

**Why:** `std::span` refers to elements owned by someone else, so its iterators stay valid after the span object is destroyed, and the standard specializes `enable_borrowed_range` for it. `vector` and `string` own their elements. `owning_view<vector<int>>` also owns the vector it holds, so it is borrowed only if the vector type is, which it is not; it is a view, but being a view and being borrowed are separate properties.

### Question 3 [warmup] ([range.range], [string.view.template.general], [range.dangling])

What does this program print?

```cpp
#include <algorithm>
#include <cstdio>
#include <string_view>

int main() {
  auto it = std::ranges::find(std::string_view("hello"), 'l');
  std::printf("%c\n", *it);
}
```

A. `l`
B. Nothing: it is ill-formed because `it` is `std::ranges::dangling`
C. Undefined behavior: the `string_view` temporary is destroyed
D. `h`

**Answer (A):** `l`

**Why:** `std::string_view` is a borrowed range: its iterators point into the string literal, which has static storage duration, not into the view object. So `find` returns a real iterator even though the `string_view` is a temporary, and dereferencing it after the view is destroyed is fine. `dangling` is only substituted for rvalue ranges that are not borrowed.

### Question 4 [tricky] ([stmt.ranged], [class.temporary])

Compiled as C++23, what does this program print?

```cpp
#include <cstdio>
#include <vector>

struct Holder {
  std::vector<int> v{1, 2, 3};
  ~Holder() { std::puts("~Holder"); }
  const std::vector<int>& items() const { return v; }
};

Holder make() { return {}; }

int main() {
  for (int x : make().items()) std::printf("%d ", x);
  std::puts("done");
}
```

A. Undefined behavior: the `Holder` is destroyed before the loop body runs
B. `~Holder` then `1 2 3 done`
C. `1 2 3 ~Holder` then `done`
D. `1 2 3 done` then `~Holder`

**Answer (C):** `1 2 3 ~Holder` then `done`

**Why:** C++23 adopted P2718: temporaries created in the for-range-initializer persist until the end of the loop, so the `Holder` returned by `make()` is destroyed after the last iteration and before `done` is printed. In C++20 only the object bound directly to `__range` had its lifetime extended, and that is a reference to a member, not the `Holder`, so the `Holder` died first and the loop read a destroyed vector; that is the first option, which is correct for older modes only.

### Question 5 [tricky] ([alg.min.max], [range.dangling])

Is this program well-defined, and what does it print?

```cpp
#include <algorithm>
#include <cstdio>
#include <vector>

std::vector<int> get() { return {3, 1, 2}; }

int main() {
  auto m = std::ranges::min(get());
  std::printf("%d\n", m);
}
```

A. Ill-formed: the result is `std::ranges::dangling`
B. Undefined behavior: `m` refers into the destroyed vector
C. Well-defined; prints `3`
D. Well-defined; prints `1`

**Answer (D):** Well-defined; prints `1`

**Why:** The range overload of `ranges::min` returns `range_value_t<R>`, a copy of the smallest element, not an iterator or reference. Nothing refers into the temporary vector after the call, so there is nothing to dangle and no reason for `dangling`. The tempting first answer applies to algorithms that return iterators, such as `ranges::min_element`, which would give `dangling` here.

### Question 6 [tricky] ([range.all.general], [range.owning.view])

In C++23, what does this program print?

```cpp
#include <cstdio>
#include <ranges>
#include <vector>

std::vector<int> get() { return {1, 2, 3}; }

int main() {
  auto r = get() | std::views::transform([](int x) { return x * 10; });
  for (int x : r) std::printf("%d ", x);
  std::puts("");
}
```

A. Nothing: piping an rvalue container into an adaptor is ill-formed
B. `10 20 30`
C. Undefined behavior: the vector is destroyed at the end of the first statement
D. Unspecified values, because `r` refers to a moved-from vector

**Answer (B):** `10 20 30`

**Why:** `views::all` moves an rvalue container that is not a view into an `owning_view`, so `r` owns the vector and the loop is safe. That rule came from P2415R2, applied to C++20 as a defect report; C++20 as originally published rejected this code, which is the tempting first answer. The undefined-behavior answer would be right if the pipeline started from a reference to a temporary's member, because that is wrapped in `ref_view` instead.

### Question 7 [standardese] ([range.range])

Which statement about the C++23 definition of `borrowed_range` is correct?

A. `borrowed_range<std::vector<int>&>` is `true`, but `borrowed_range<std::vector<int>>` is `false`
B. Both are `false`, because a vector owns its elements
C. Both are `true`, because `std::vector` iterators are pointers in practice
D. `borrowed_range` is only defined for types that model `view`

**Answer (A):** `borrowed_range<std::vector<int>&>` is `true`, but `borrowed_range<std::vector<int>>` is `false`

**Why:** The concept is `range<R> && (is_lvalue_reference_v<R> || enable_borrowed_range<remove_cvref_t<R>>)`. An lvalue reference is always borrowed, because an algorithm receiving one is not responsible for the object's lifetime. A non-reference `vector<int>`, the case of an rvalue argument, is borrowed only if `enable_borrowed_range` says so, and it does not. Views are not required: `subrange` and `span` are views, but the concept applies to any range.

### Question 8 [standardese] ([class.temporary], [stmt.ranged])

In C++23, which temporaries created while evaluating the initializer of a range-based `for` have their lifetime extended to the end of the loop?

A. Only the temporary bound directly to the hidden `__range` reference, as in C++11
B. Only temporaries of class type with a non-trivial destructor
C. Every temporary that would otherwise be destroyed at the end of the for-range-initializer full-expression
D. None: the initializer must not create temporaries other than the range itself

**Answer (C):** Every temporary that would otherwise be destroyed at the end of the for-range-initializer full-expression

**Why:** P2718 added a context to [class.temporary]: a temporary created in the for-range-initializer that would be destroyed at the end of that full-expression instead persists for the lifetime of the `__range` reference, which is the whole loop. Before C++23, only the temporary bound directly to the reference was extended, which is the first option. The rule covers all such temporaries regardless of type, but only in range-based `for`, not in other declarations.

# Range adaptors and pipelines

> A range adaptor turns one view into another lazily, and the pipe operator only rearranges the call. What each adaptor keeps of its input's iterator category, and what it caches, decides where a pipeline compiles, how often your functions run, and when it quietly misbehaves.

- **Source:** C++ Atlas (https://cppatlas.com/topics/range-adaptors-and-pipelines)
- **Track:** Iterators, algorithms and ranges
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [range.adaptor.object] (https://eel.is/c++draft/range.adaptor.object), [range.range] (https://eel.is/c++draft/range.range), [range.filter] (https://eel.is/c++draft/range.filter), [range.filter.iterator] (https://eel.is/c++draft/range.filter.iterator), [range.transform] (https://eel.is/c++draft/range.transform), [range.take] (https://eel.is/c++draft/range.take), [range.split] (https://eel.is/c++draft/range.split), [range.lazy.split] (https://eel.is/c++draft/range.lazy.split), [range.join] (https://eel.is/c++draft/range.join), [range.zip] (https://eel.is/c++draft/range.zip), [range.enumerate] (https://eel.is/c++draft/range.enumerate), [range.chunk] (https://eel.is/c++draft/range.chunk), [range.slide] (https://eel.is/c++draft/range.slide), [range.stride] (https://eel.is/c++draft/range.stride), [range.cartesian] (https://eel.is/c++draft/range.cartesian)
- **cppreference links:** [Ranges library (range adaptors)](https://en.cppreference.com/w/cpp/ranges), [std::ranges::range_adaptor_closure](https://en.cppreference.com/w/cpp/ranges/range_adaptor_closure), [std::ranges::filter_view](https://en.cppreference.com/w/cpp/ranges/filter_view), [std::ranges::transform_view](https://en.cppreference.com/w/cpp/ranges/transform_view), [std::ranges::take_view](https://en.cppreference.com/w/cpp/ranges/take_view), [std::ranges::zip_view](https://en.cppreference.com/w/cpp/ranges/zip_view)
- **Prerequisites:** ranges-and-views, iterator-categories-and-concepts, lambdas

## The one idea

A pipeline such as `xs | views::filter(p) | views::transform(f)` does no work when you write it. It builds a nested type, here a `transform_view` of a `filter_view` of a `ref_view` of `xs`, and every element is computed on demand when someone dereferences and increments its iterators. The pipe is only notation. `r | views::filter(p)` means exactly `views::filter(r, p)`.

Two consequences follow from laziness, and most surprises in this area come from one or the other. First, each layer can only offer what its input offers, and often less: an adaptor that cannot jump ahead in constant time turns a random-access range into a bidirectional one. Second, because work happens at iteration time, a function in the pipeline runs whenever an iterator is dereferenced, which may be more than once per element, and a view may remember results from an earlier pass.

> **Mental model.** A pipeline is a recipe, not a container. Each adaptor wraps the iterator of the layer below it, so the category, the cost of dereferencing, and any cached state are those of the wrapped iterators, layer by layer.

What a view is, and how `views::all` chooses between `ref_view` and `owning_view`, is covered in the ranges-and-views topic. This topic is about the adaptors themselves.

## Adaptor objects, closures, and how the pipe composes

Every name in `std::views` is a function object, not a function. [range.adaptor.object] gives them two shapes.

A **range adaptor closure object** takes exactly one range. `views::reverse`, `views::join`, `views::enumerate`, `views::as_const`, `views::as_rvalue` and `views::common` are closures already. For a closure `C`, the expressions `C(r)` and `r | C` are equivalent.

A **range adaptor object** takes a range plus extra arguments, like `views::filter(r, p)` or `views::take(r, 3)`. Calling it with only the extra arguments returns a closure that stores them, so `views::filter(p)` is a closure, and `r | views::filter(p)` calls it with `r` in front.

Two closures can be piped together without a range. `C | D` produces a new closure such that `r | (C | D)` is equivalent to `r | C | D`, which is `D(C(r))`. Because the pipe is left-associative, the order you read is the order data flows.

```cpp
#include <ranges>
#include <vector>
#include <cstdio>
namespace views = std::views;

int main() {
  auto even_squares = views::filter([](int x) { return x % 2 == 0; })
                    | views::transform([](int x) { return x * x; });
  std::vector<int> xs{1, 2, 3, 4};
  for (int x : xs | even_squares) std::printf("%d ", x);  // prints 4 16
}
```

Not everything in `std::views` is pipeable. `views::zip`, `views::cartesian_product` and the C++26 `views::concat` take any number of ranges, so they are customization point objects rather than adaptor objects. `views::zip(ys)` is a perfectly good one-range zip view, which means `xs | views::zip(ys)` tries to pipe `xs` into a view and fails to compile. Write `views::zip(xs, ys)`.

## The adaptors worth knowing

The C++20 core covers selection and reshaping. `filter` keeps elements satisfying a predicate. `transform` applies a function at dereference time. `take` and `drop` keep or skip a count, and `take_while` and `drop_while` do the same by predicate. `join` flattens a range of ranges. `split` breaks a range into subranges at a delimiter. `reverse`, `keys`, `values` and `elements` round out the set.

C++23 added the adaptors people used to borrow from range-v3. `zip` walks several ranges in lockstep and yields tuples of references, stopping at the shortest. `enumerate` pairs each element with its index. `chunk(n)` cuts a range into non-overlapping pieces of `n`, the last possibly shorter, and `slide(n)` yields every overlapping window of `n`. `stride(n)` keeps every `n`th element. `cartesian_product` yields every combination of elements from several ranges. `as_rvalue` makes elements rvalues so a consumer can move from them, and `as_const` makes them const.

`split` and `lazy_split` deserve a note. They swapped names by a defect report against C++20 (P2210). `split` now needs a forward range, and each piece it yields is a `subrange` of the underlying iterators, so splitting a `string_view` gives pieces you can convert to `string_view`. `lazy_split` also works on input ranges, such as a stream, but each piece is a lazily searched range that is never even bidirectional.

```cpp
#include <ranges>
#include <string_view>
using namespace std::literals;

void pieces() {
  for (auto w : "a,b,,c"sv | std::views::split(','))
    std::string_view s(w);                     // OK: w is a contiguous subrange
  // for (auto w : "a b"sv | std::views::lazy_split(' '))
  //   std::string_view s(w);                  // error: no such conversion
}
```

## What each adaptor keeps and loses

An adaptor's iterator can only be as strong as the operations it can implement in constant time. Expect these from the common adaptors:

| Adaptor | Best category | Sized | Notes |
| --- | --- | --- | --- |
| `filter` | bidirectional | never | common if the input is common |
| `transform` | random access | if input is | never contiguous |
| `take` | input's category | if input is | common only if input is sized and random access |
| `drop` | input's category | if input is | caches `begin()` unless random access and sized |
| `join` | bidirectional | never | needs inner ranges bidirectional and common |
| `zip` | weakest of inputs | if all are | size is the minimum |
| `split` | forward | never | pieces keep the input's category |
| `chunk`, `stride` | input's category | if input is | `chunk` on an input range is input only |
| `slide` | input's category | if input is | needs a forward range |

`filter` cannot know how far apart two matching elements are, so it can never be random access or sized, and `ranges::size` does not compile on it. `transform` loses contiguity because the elements it yields are computed, not stored. `take` is the subtle one: on a `std::list`, it knows its size but cannot compute its end iterator in constant time, so it pairs a `counted_iterator` with `default_sentinel` and stops being a common range.

```cpp
#include <list>
#include <ranges>
#include <vector>

std::list<int> l{1, 2, 3};
std::vector<int> v{1, 2, 3};
static_assert(std::ranges::sized_range<decltype(l | std::views::take(2))>);
static_assert(!std::ranges::common_range<decltype(l | std::views::take(2))>);
static_assert(std::ranges::common_range<decltype(v | std::views::take(2))>);
```

Some adaptors do not wrap at all when they can return a cheaper type. `take` and `drop` applied to a `std::span`, a `std::basic_string_view`, a sized `iota_view` or a suitable `subrange` return that same kind of type, so `span | views::take(2)` is a `std::span`. `views::reverse` applied to a `reverse_view` unwraps it instead of stacking another layer.

## Functions run on every dereference

`transform` calls its function inside `operator*`. It does not store the result. `filter` must dereference elements to test them. Put `transform` before `filter`, and each element that passes is computed once to be tested and again when the loop reads it.

```cpp
#include <ranges>
#include <vector>
#include <cstdio>

int main() {
  int calls = 0;
  std::vector<int> xs{1, 2, 3, 4};
  auto r = xs | std::views::transform([&](int x) { ++calls; return x * x; })
              | std::views::filter([](int x) { return x % 2 == 0; });
  for (int x : r) (void)x;
  std::printf("%d\n", calls);  // prints 6: four tests plus two reads
}
```

For a cheap function this does not matter. For an expensive or side-effecting one, filter first when you can, or materialize the transformed values with `std::ranges::to`. A function in a view should be regular in the sense of the `regular_invocable` concept: same input, same output, no observable side effects. A counter, as above, is fine for measuring and wrong for logic.

> **Pitfall.** Writing through a `filter_view` is allowed, but if the new value no longer satisfies the predicate, the behaviour is undefined. A loop like `for (int& x : v | views::filter(is_even)) ++x;` breaks the view's invariant for every element it touches.

> **Standardese.** [range.filter.iterator] says that modifying the element a `filter_view` iterator denotes is permitted, but results in undefined behavior if the resulting value does not satisfy the filter predicate. The view never re-tests a position it has already accepted, so nothing diagnoses the violation.

## Caching, and why some views cannot be const

The `range` concept requires `ranges::begin` and `ranges::end` to run in amortized constant time ([range.range]). `filter_view` has to search for its first matching element, which is linear. To meet the requirement it searches once and caches the iterator inside the view. `drop_view` caches unless its input is random access and sized, `reverse_view` caches when its input is not a common range, and `split_view` and `chunk_by_view` always cache.

Caching mutates the view, so those `begin()` members are not `const`. A `const filter_view` is not a range at all, and a function template that takes its argument as `const auto&` cannot iterate it.

```cpp
#include <ranges>
#include <vector>
#include <cstdio>

void print(const auto& r) { for (int x : r) std::printf("%d ", x); }

void demo(std::vector<int>& xs) {
  print(xs | std::views::transform([](int x) { return x + 1; }));  // OK
  // print(xs | std::views::filter([](int x) { return x > 1; }));
  // error: filter_view::begin() is not const
}
```

Take views by forwarding reference, `auto&&`, or by value, since views are cheap to copy or move. The cache also outlives changes to the underlying data. If you iterate a filter view, then change the first elements of the vector so that an earlier element would now match, the next iteration still starts from the cached position. Treat a cached view as single-use when its underlying data changes; recreate it rather than reuse it.

## Writing your own adaptor

C++23 added `std::ranges::range_adaptor_closure<D>`. Derive from it using the curiously recurring pattern, give your type a call operator that takes a range, and your object gains the pipe: `r | yours` calls it, and `yours | other` composes with any standard closure. The type must have exactly one such base and must not itself be a range.

```cpp
#include <ranges>
#include <vector>
#include <cstdio>

struct evens_fn : std::ranges::range_adaptor_closure<evens_fn> {
  template <std::ranges::viewable_range R>
  constexpr auto operator()(R&& r) const {
    return std::forward<R>(r) | std::views::filter([](int x) { return x % 2 == 0; });
  }
};
inline constexpr evens_fn evens;

int main() {
  std::vector<int> xs{1, 2, 3, 4, 5, 6};
  auto pipeline = evens | std::views::transform([](int x) { return x * 10; })
                | std::views::take(2);
  for (int x : xs | pipeline) std::printf("%d ", x);  // prints 20 40
}
```

For an adaptor that takes arguments, store them as members of the closure, as `evens_fn` could store a divisor, or produce the closure with `std::bind_back` over an adaptor object. In C++20 there was no portable way to do this; libraries relied on each implementation's internal base class.

## What to remember

- `r | A(args)` is `A(r, args)`, and `r | (C | D)` is `D(C(r))`; the pipe adds nothing but syntax.
- `zip`, `cartesian_product` and C++26 `concat` are not adaptor objects; call them with all their ranges.
- `filter` is at most bidirectional and never sized; `transform` is never contiguous; `take` on a non-random-access range is not common.
- `take` and `drop` return a `span`, `string_view` or `iota_view` when given one, instead of wrapping it.
- `split` needs a forward range and yields subranges; `lazy_split` accepts input ranges but its pieces are weak.
- `transform` before `filter` calls the function twice for every element that passes.
- Writing a value through a `filter_view` that fails the predicate is undefined behaviour.
- Views that cache `begin()`, such as `filter`, `split`, and `drop` over a non-random-access input, cannot be iterated as const; pass views by `auto&&` or by value.
- C++23 `range_adaptor_closure` lets your own function objects join a pipeline.

## Concept Map Outline

- **Range adaptors and pipelines:** Lazy views built from adaptor objects; the pipe only rearranges the call.
  - **Adaptor objects:** Every views:: name is a function object, specified in [range.adaptor.object].
    - **Closure objects:** Take one range; C(r) and r | C are equivalent, as with views::reverse or views::join.
    - **Partial application:** views::filter(p) stores p and returns a closure; r | views::filter(p) is views::filter(r, p).
    - **Composing closures:** C | D is a closure, and r | (C | D) means D(C(r)), the same as r | C | D.
    - **Not pipeable:** zip, cartesian_product and concat take many ranges; xs | views::zip(ys) does not compile.
  - **Adaptors to know:** C++20 gave selection and reshaping; C++23 added the range-v3 favourites.
    - **C++20 core:** filter, transform, take, drop, take_while, drop_while, join, split, reverse, keys, values.
    - **C++23 additions:** zip, enumerate, chunk, slide, stride, cartesian_product, as_rvalue, as_const.
    - **split vs lazy_split:** split needs a forward range and yields subranges; lazy_split takes input ranges, weak pieces.
  - **Category kept or lost:** An adaptor offers only what it can do in constant time on its input.
    - **filter:** At most bidirectional and never sized, since gaps between matches are unknown.
    - **transform:** Keeps random access and size but is never contiguous: values are computed.
    - **take on a list:** Sized but not common: counted_iterator paired with default_sentinel.
    - **Cheaper return types:** take and drop on span, string_view or sized iota_view return that same kind of type.
  - **Evaluation surprises:** Work happens at dereference time, every time.
    - **transform then filter:** The function runs once to test and again to read every element that passes.
    - **Writing through filter:** Undefined behavior if the new value fails the predicate, per [range.filter.iterator].
    - **Regular functions:** transform and filter require regular_invocable: same input, same output.
  - **Caching:** begin() must be amortized O(1), so some views remember their first position.
    - **Who caches:** filter, split, chunk_by, drop on non-random-access inputs, reverse on non-common inputs.
    - **No const iteration:** Caching begin() is non-const, so a const filter_view is not a range.
    - **Stale cache:** Changing underlying data after a pass does not move the cached begin; recreate the view.
  - **Custom adaptors:** C++23 range_adaptor_closure gives your own function object the pipe.
    - **CRTP base:** Derive D from range_adaptor_closure<D> exactly once; D must not itself be a range.
    - **Arguments:** Store them as members, or build the closure with std::bind_back over an adaptor.

## Standardese Quiz Questions

### Question 1 [warmup] ([range.adaptor.object])

What does this program print?

```cpp
#include <cstdio>
#include <ranges>
#include <vector>

int main() {
  auto p = std::views::transform([](int x) { return x * 10; })
         | std::views::filter([](int x) { return x > 15; });
  std::vector<int> xs{1, 2, 3};
  for (int x : xs | p) std::printf("%d ", x);
}
```

A. `10 20 30 `
B. `2 3 `
C. `20 30 `
D. Nothing: a closure cannot be composed before it is applied to a range

**Answer (C):** `20 30 `

**Why:** Piping two closures together yields a closure `p` such that `xs | p` is `xs | transform(...) | filter(...)`, so data flows left to right. The transform runs first, giving 10, 20 and 30, and the filter keeps the values above 15. The answer `2 3 ` would be right if the filter were applied before the transform, which is the order a reader of nested function calls might expect.

### Question 2 [warmup] ([range.zip], [range.adaptor.object])

In C++23, what happens with the marked line?

```cpp
#include <ranges>
#include <vector>

int main() {
  std::vector<int> xs{1, 2, 3};
  std::vector<int> ys{4, 5, 6};
  auto z = xs | std::views::zip(ys);  // this line
  (void)z;
}
```

A. It produces a view of the tuples (1, 4), (2, 5) and (3, 6)
B. It is ill-formed: `views::zip(ys)` is already a one-range zip view, and a range cannot be piped into a view
C. It produces a view of the tuples (4, 1), (5, 2) and (6, 3)
D. It compiles, but iterating it is undefined behavior

**Answer (B):** It is ill-formed: `views::zip(ys)` is already a one-range zip view, and a range cannot be piped into a view

**Why:** `views::zip` is a customization point object that takes any number of ranges, not a range adaptor object with partial application. `views::zip(ys)` is a complete `zip_view` over one range, and there is no `operator|` taking a vector on the left and a view on the right, so the line does not compile. Write `views::zip(xs, ys)` instead.

### Question 3 [warmup] ([range.transform], [range.filter.iterator])

What does this program print?

```cpp
#include <cstdio>
#include <ranges>
#include <vector>

int main() {
  int calls = 0;
  std::vector<int> xs{1, 2, 3, 4};
  auto r = xs | std::views::transform([&](int x) { ++calls; return x * x; })
              | std::views::filter([](int x) { return x % 2 == 0; });
  for (int x : r) (void)x;
  std::printf("%d\n", calls);
}
```

A. `4`
B. `2`
C. `8`
D. `6`

**Answer (D):** `6`

**Why:** The filter dereferences each of the four transformed elements to test it, which calls the function four times. The range-based for then dereferences the filter iterator at the two elements that passed, 4 and 16, and a transform iterator recomputes its value on every dereference, adding two more calls. `4` is the tempting answer if you assume the transform caches its result; it does not.

### Question 4 [tricky] ([range.take.view], [iterators.counted])

Which of these static assertions fails?

```cpp
#include <list>
#include <ranges>

std::list<int> l{1, 2, 3};
using T = decltype(l | std::views::take(2));

static_assert(std::ranges::bidirectional_range<T>);  // A
static_assert(std::ranges::sized_range<T>);          // B
static_assert(std::ranges::common_range<T>);         // C
static_assert(std::ranges::view<T>);                 // D
```

A. A: `take` on a list is only a forward range
B. B: `take` never knows its size
C. C: the iterator and sentinel types differ
D. None of them fails

**Answer (C):** C: the iterator and sentinel types differ

**Why:** `take_view` is common only when its input is both sized and random access, because only then can it compute its end iterator as `begin() + n`. For a sized list it instead uses a `counted_iterator` as the iterator and `default_sentinel_t` as the sentinel, so the view is sized and bidirectional but not common. Assertion A holds because `take` preserves the input's category, and B holds because a list is sized. Assertion C therefore fails and the program does not compile.

### Question 5 [tricky] ([range.filter.view], [range.range])

Which call to `print` is ill-formed?

```cpp
#include <cstdio>
#include <ranges>
#include <vector>

void print(const auto& r) { for (int x : r) std::printf("%d ", x); }

int main() {
  std::vector<int> xs{1, 2, 3};
  print(xs | std::views::transform([](int x) { return x + 1; }));  // 1
  print(xs | std::views::filter([](int x) { return x > 1; }));     // 2
  print(xs | std::views::take(2));                                 // 3
}
```

A. Only call 2
B. Calls 1 and 2, because both store a lambda
C. None of them; all three views are const-iterable
D. All three, because a view must not be passed by const reference

**Answer (A):** Only call 2

**Why:** `filter_view::begin()` caches the first matching position to meet the amortized constant-time requirement of `range`, so it is a non-const member, a `const filter_view` is not a range, and call 2 is ill-formed. `transform_view` and `take_view` over a `ref_view` provide const `begin()` members, so calls 1 and 3 compile. Storing a lambda is not the problem; caching is.

### Question 6 [tricky] ([range.take.overview])

What is the type of `t`?

```cpp
#include <ranges>
#include <span>
#include <vector>

std::vector<int> v{1, 2, 3, 4};
std::span<int> s(v);
auto t = s | std::views::take(2);
```

A. `std::ranges::take_view<std::span<int>>`
B. `std::ranges::take_view<std::ranges::ref_view<std::span<int>>>`
C. `std::ranges::subrange<int*>`
D. `std::span<int>`

**Answer (D):** `std::span<int>`

**Why:** `views::take` is specified to return a cheaper type when it can: for a `std::span` it returns a `span` of the first `n` elements, and it does the same for `basic_string_view`, sized random-access `iota_view` and suitable `subrange` specializations. The `take_view` answers describe what you get for a general view. A span is itself a view, so it would never be wrapped in a `ref_view` either.

### Question 7 [standardese] ([range.filter.iterator])

What does the standard say about this program?

```cpp
#include <ranges>
#include <vector>

int main() {
  std::vector<int> v{2, 4, 6};
  for (int& x : v | std::views::filter([](int x) { return x % 2 == 0; }))
    ++x;
}
```

A. It is ill-formed: a `filter_view` yields const references
B. It is well-defined and leaves `v` as `{3, 5, 7}`
C. It has undefined behavior
D. The final contents of `v` are unspecified

**Answer (C):** It has undefined behavior

**Why:** [range.filter.iterator] permits modifying the element a `filter_view` iterator denotes, but the behavior is undefined if the new value does not satisfy the predicate. Each increment makes an even number odd. In practice you will likely observe `{3, 5, 7}`, which is why the second option is tempting, but the standard gives no such guarantee. The references are not const, so the code does compile.

### Question 8 [standardese] ([range.adaptor.object])

For range adaptor closure objects `C` and `D` and a viewable range `r`, what does [range.adaptor.object] make `r | (C | D)` equivalent to?

A. `C(D(r))`
B. `D(C(r))`
C. Either order; it is unspecified
D. Nothing: closures only combine with ranges

**Answer (B):** `D(C(r))`

**Why:** The standard defines `C | D` as a closure whose application to `r` is `D(C(r))`, which is the same as `r | C | D`. That is what makes a stored pipeline behave exactly like writing the stages out inline. `C(D(r))` is how function composition is often written in mathematics, which makes it the tempting choice.

# Strict weak ordering and comparators

> Every sorting algorithm and ordered container assumes its comparator is a strict weak ordering, and a comparator that is not one gives undefined behavior rather than a merely odd order. Knowing the four laws, and the equivalence they define, explains which comparators are safe and why ordered lookup ignores operator==.

- **Source:** C++ Atlas (https://cppatlas.com/topics/strict-weak-ordering-and-comparators)
- **Track:** Iterators, algorithms and ranges
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [alg.sorting.general] (https://eel.is/c++draft/alg.sorting.general), [concept.strictweakorder] (https://eel.is/c++draft/concept.strictweakorder), [associative.reqmts.general] (https://eel.is/c++draft/associative.reqmts.general), [sort] (https://eel.is/c++draft/sort), [stable.sort] (https://eel.is/c++draft/stable.sort), [range.cmp] (https://eel.is/c++draft/range.cmp), [cmp.alg] (https://eel.is/c++draft/cmp.alg), [res.on.functions] (https://eel.is/c++draft/res.on.functions)
- **cppreference links:** [C++ named requirements: Compare](https://en.cppreference.com/w/cpp/named_req/Compare), [std::strict_weak_order](https://en.cppreference.com/w/cpp/concepts/strict_weak_order), [std::sort](https://en.cppreference.com/w/cpp/algorithm/sort), [std::stable_sort](https://en.cppreference.com/w/cpp/algorithm/stable_sort), [std::ranges::less](https://en.cppreference.com/w/cpp/utility/functional/ranges/less), [std::strong_order](https://en.cppreference.com/w/cpp/utility/compare/strong_order)
- **Prerequisites:** algorithms, three-way-comparison, associative-and-unordered-containers

## The one idea

A comparator answers one question: must `a` come before `b`? Algorithms like `std::sort` and containers like `std::set` never ask whether two elements are equal. They infer it. If neither has to come before the other, the two are treated as interchangeable, or **equivalent**. Everything the library does with a comparator, from partitioning around a pivot to rejecting a duplicate key, relies on that inference being consistent.

A **strict weak ordering** is precisely the condition under which the inference is consistent. It sorts the values into groups of equivalent elements and lines the groups up in a total order. If your comparator does not have that shape, the library is not obliged to produce a wrong-but-valid order. It is allowed to do anything, and real implementations read past the end of the array.

> **Mental model.** A strict weak ordering is a ranking with ties. Equivalent elements share a rank, every rank is strictly before or after every other, and `comp(a, b)` means "a's rank is lower".

## The four laws

For a comparator `comp`, define `equiv(a, b)` as `!comp(a, b) && !comp(b, a)`. [alg.sorting.general] requires, and the `strict_weak_order` concept documents, that `comp` is:

1. **Irreflexive.** `comp(a, a)` is false. Nothing comes before itself.
2. **Asymmetric.** If `comp(a, b)` then not `comp(b, a)`. This follows from the other laws but is the one most often broken directly.
3. **Transitive.** If `comp(a, b)` and `comp(b, c)` then `comp(a, c)`.
4. **Transitive in incomparability.** If `equiv(a, b)` and `equiv(b, c)` then `equiv(a, c)`.

The fourth law is what makes it *weak* rather than *partial*. Under the first three alone, incomparable elements can sit in no consistent position: `a` might tie with `b`, `b` with `c`, yet `a` come strictly before `c`. Law four rules that out, so equivalence is a genuine equivalence relation and the classes it forms are totally ordered.

> **Standardese.** [alg.sorting.general] says that, for every algorithm other than the binary searches, `comp` shall induce a strict weak ordering on the values, and defines equivalence as `!comp(a, b) && !comp(b, a)`. The binary searches only need the range to be partitioned with respect to the value sought. Breaking a library requirement placed on a user-supplied function object is undefined behavior by [res.on.functions].

## Comparators that break the laws

The usual suspects each break a specific law.

**Using `<=` or `>=`** breaks irreflexivity. `comp(x, x)` is true, so equal elements each claim to come first. In libstdc++, `std::sort` uses an unguarded insertion step that trusts `comp(x, x)` to be false as a stopping condition. With enough equal elements it walks off the front of the buffer. The debug mode, `-D_GLIBCXX_DEBUG`, checks irreflexivity and aborts with a diagnostic instead.

```cpp
#include <algorithm>
#include <vector>

void bad(std::vector<int>& v) {
  std::sort(v.begin(), v.end(), [](int a, int b) { return a <= b; });
  // undefined behavior: comp(x, x) is true
}
```

**NaN** breaks transitivity of incomparability. With `<` on doubles, NaN is incomparable to every value, so `1.0` ties with NaN and NaN ties with `2.0`, yet `1.0 < 2.0`. One NaN in a `std::vector<double>` makes `std::sort` with the default comparator undefined behavior, and `std::set<double>` lookups unreliable.

**An inconsistent multi-key comparison** breaks asymmetry. The classic mistake reads like a reasonable rule.

```cpp
struct Pt { int x, y; };

bool wrong(const Pt& a, const Pt& b) {
  return a.x < b.x || a.y < b.y;
}
// wrong({1, 2}, {2, 1}) and wrong({2, 1}, {1, 2}) are both true
```

**State that changes between calls**, such as a comparator that consults a random number generator or a mutable cache keyed on call order, breaks all four at once. A comparator may count its calls, but its answer must depend only on the two arguments.

> **Pitfall.** Undefined behavior from a bad comparator rarely shows up in small tests. The out-of-bounds read in introsort needs runs of equal elements longer than the insertion threshold, typically more than sixteen, so a comparator using `<=` can pass every unit test and crash on production data.

## Writing multi-key comparators correctly

Compare the first key; only when it ties, move on to the next. `std::tie` builds tuples of references and their `<` does exactly that lexicographic walk.

```cpp
#include <string>
#include <tuple>

struct Person { std::string name; int age; };

bool by_age_then_name(const Person& a, const Person& b) {
  return std::tie(a.age, a.name) < std::tie(b.age, b.name);
}
```

`std::tie` needs lvalues. For a derived key such as `a.name.size()`, use `std::forward_as_tuple` or `std::make_tuple`, or spell out the comparison. Since C++20, three-way comparison makes the manual version compact, and `auto operator<=>(const Person&) const = default;` gives memberwise lexicographic ordering in declaration order without a comparator at all. The three-way-comparison topic covers the defaulting rules.

```cpp
#include <compare>
#include <string>

struct Person { std::string name; int age; };

bool by_age_desc_then_name(const Person& a, const Person& b) {
  if (auto c = b.age <=> a.age; c != 0) return c < 0;  // age descending
  return a.name < b.name;
}
```

For floating-point keys, choose what NaN means. `std::strong_order` on IEEE types is a total order that places NaNs consistently and also orders `-0.0` before `+0.0`, so `[](double a, double b) { return std::strong_order(a, b) < 0; }` is a valid comparator for any input. `std::partial_order(a, b) < 0` is not: it is `<` again, NaN problem included.

## Equivalence versus equality

Because ordered containers use equivalence, `operator==` plays no part in their lookup. A case-insensitive `std::set<std::string, CaseLess>` treats `"Apple"` and `"APPLE"` as the same key: inserting the second fails, and `find`, `count` and `contains` locate the first. Generic algorithms that search for a value, such as `std::ranges::find`, use `==` instead, so they disagree with the container.

```cpp
#include <algorithm>
#include <cctype>
#include <set>
#include <string>

struct CaseLess {
  bool operator()(const std::string& a, const std::string& b) const {
    auto lower = [](unsigned char c) { return std::tolower(c); };
    return std::ranges::lexicographical_compare(a, b, {}, lower, lower);
  }
};

void demo() {
  std::set<std::string, CaseLess> s{"Apple"};
  s.insert("APPLE");                        // not inserted: equivalent key
  bool a = s.contains("apple");             // true
  bool b = std::ranges::find(s, std::string("APPLE")) != s.end();  // false
  (void)a; (void)b;
}
```

A comparator that is not a strict weak ordering does more damage in a container than in a sort, because the damage persists. `std::set<int, std::less_equal<int>>` never sees two equal keys as equivalent, so it stores duplicates and then cannot find them. That is undefined behavior too, since [associative.reqmts.general] requires the container's comparator to induce a strict weak ordering on keys. Transparent comparators like `std::less<>` and heterogeneous lookup are covered in the node-handles-and-heterogeneous-lookup topic.

## sort, stable_sort, and what equivalent elements do

`std::sort` puts equivalent elements next to each other in an unspecified relative order. Since C++11 it performs O(N log N) comparisons in the worst case; before that only the average case was specified. `std::stable_sort` keeps equivalent elements in their original relative order. It is O(N log N) when it can allocate a buffer and O(N log² N) when it cannot. `std::list::sort` and `std::forward_list::sort` are stable too.

Stability is what lets you sort by several keys in passes, least significant key first, and it is the only reason to pay the extra cost. If the full sort key is a strict total order, the two algorithms give identical results.

Other algorithms also make promises about equivalent elements, and those promises are only as good as your comparator. `std::max(a, b)` and `std::min(a, b)` both return their first argument when the two are equivalent, so `std::min` and `std::max` of the same equivalent pair return the same object. `std::merge` takes from the first range before the second among equivalent elements, and `std::equal_range` returns exactly the run of elements equivalent to the value. Each of these is a statement about equivalence classes, and none means anything if the classes are not well formed.

## ranges::less, the concept, and projections

`std::ranges::less` is the default comparator for the constrained algorithms. Unlike `std::less<>`, it is constrained with `totally_ordered_with`, so comparing types with no `<` fails at the call rather than deep inside an algorithm. Both produce a strict total order over pointers, which built-in `<` does not guarantee for unrelated objects.

The `strict_weak_order<R, T, U>` concept, used by `std::sortable` through `indirect_strict_weak_order`, checks only syntax: `R` must be a predicate callable with every combination of `T` and `U`. The laws themselves are semantic requirements that no compiler checks. `std::strict_weak_order<std::ranges::less_equal, int, int>` is satisfied.

The constrained algorithms also take a **projection**, applied to each element before the comparator sees it. Projections replace most hand-written key comparators, and the comparator argument can be left as `{}` to keep `ranges::less`.

```cpp
#include <algorithm>
#include <functional>
#include <string>
#include <vector>

struct Person { std::string name; int age; };

void demo(std::vector<Person>& people) {
  std::ranges::sort(people, std::ranges::greater{}, &Person::name);
  std::ranges::sort(people, {}, &Person::age);                   // by age
  auto it = std::ranges::lower_bound(people, 30, {}, &Person::age);
  // it: the first person aged 30 or more
  (void)it;
}
```

In a binary search, the projection is applied to the elements only, never to the value searched for, which is why `lower_bound(people, 30, {}, &Person::age)` compares ages with `30`. The range must already be ordered by that same projected key. Had the two sorts run in the opposite order, the people would be ordered by name, and the search would violate its precondition.

## What to remember

- Library comparators must be strict weak orderings: irreflexive, asymmetric, transitive, and transitive in incomparability.
- Equivalence is `!comp(a, b) && !comp(b, a)`; ordered containers and sorts use it, never `==`.
- Violating the laws is undefined behavior, not an odd order; `<=` can make `std::sort` read out of bounds.
- NaN with `<` breaks transitivity of incomparability; use `std::strong_order` or remove NaNs first.
- Write multi-key comparisons with `std::tie`, `<=>`, or a defaulted `operator<=>`, never `a.x < b.x || a.y < b.y`.
- `std::sort` leaves equivalent elements in unspecified order; `std::stable_sort` and `list::sort` preserve it.
- The `strict_weak_order` concept is syntactic; `ranges::less_equal` satisfies it.
- Projections apply to elements, not to the searched value, and the range must be ordered by the projected key.

## Concept Map Outline

- **Strict weak ordering:** The shape every library comparator must have: a ranking with ties.
  - **The four laws:** Required by [alg.sorting.general] for sorting and ordered containers.
    - **Irreflexive:** comp(a, a) is false: nothing comes before itself.
    - **Asymmetric:** If comp(a, b) then not comp(b, a).
    - **Transitive:** comp(a, b) and comp(b, c) imply comp(a, c).
    - **Incomparability transitive:** Ties chain: equiv(a, b) and equiv(b, c) imply equiv(a, c); this makes it weak, not partial.
  - **Equivalence:** equiv(a, b) is !comp(a, b) && !comp(b, a); operator== is never consulted.
    - **Set lookup:** find, count and contains locate equivalent keys; a case-insensitive set rejects "APPLE" after "Apple".
    - **ranges::find differs:** Generic searches use ==, so they can disagree with the container's own lookup.
    - **min, max, merge:** On equivalent arguments min and max return the first; merge takes from the first range first.
  - **Broken comparators:** Violating the laws is undefined behavior, not an odd but valid order.
    - **<= or >=:** Breaks irreflexivity; libstdc++ sort can read out of bounds on long runs of equal values.
    - **NaN with <:** NaN ties with everything, so incomparability is not transitive.
    - **OR of two keys:** Breaks asymmetry: (1,2) and (2,1) each come before the other.
    - **Debug checking:** -D_GLIBCXX_DEBUG checks irreflexivity in std::sort; release builds check nothing.
  - **Writing them right:** Compare the next key only when the previous keys tie.
    - **std::tie:** tie(a.x, a.y) < tie(b.x, b.y) compares lexicographically; needs lvalues.
    - **<=> chains:** if (auto c = a.k <=> b.k; c != 0) return c < 0; then the next key.
    - **strong_order for doubles:** std::strong_order(a, b) < 0 is a total order that also orders NaN and signed zeros.
  - **sort vs stable_sort:** They differ only in what happens to equivalent elements.
    - **sort:** O(N log N) comparisons in the worst case since C++11; equivalent order unspecified.
    - **stable_sort:** Keeps equivalent elements in input order; O(N log^2 N) if no buffer is available.
  - **Ranges tools:** Constrained algorithms add concepts and projections.
    - **ranges::less:** Default comparator, constrained by totally_ordered_with; total order over pointers.
    - **strict_weak_order concept:** Purely syntactic: ranges::less_equal satisfies it.
    - **Projections:** Applied to elements, not to the searched value; ranges::sort(v, {}, &P::age).

## Standardese Quiz Questions

### Question 1 [warmup] ([associative.reqmts.general], [alg.sorting.general])

What does this program print?

```cpp
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <set>
#include <string>

struct CaseLess {
  bool operator()(const std::string& a, const std::string& b) const {
    auto lower = [](unsigned char c) { return std::tolower(c); };
    return std::ranges::lexicographical_compare(a, b, {}, lower, lower);
  }
};

int main() {
  std::set<std::string, CaseLess> s{"Apple"};
  auto [it, inserted] = s.insert("APPLE");
  std::printf("%zu %d %s\n", s.size(), inserted, it->c_str());
}
```

A. `2 1 APPLE`
B. `1 0 Apple`
C. `1 1 APPLE`
D. `1 0` followed by either spelling; which one is kept is unspecified

**Answer (B):** `1 0 Apple`

**Why:** `std::set` decides whether a key is already present by equivalence under its comparator, `!comp(a, b) && !comp(b, a)`, and the two strings are equivalent when compared case-insensitively. The insertion is rejected, `inserted` is false, and the returned iterator points at the existing element, which keeps its original spelling. `2 1 APPLE` is what you would expect if the set used `operator==`, which it never does. Which element survives is not unspecified: the existing element is never replaced by a rejected insertion.

### Question 2 [warmup] ([alg.sorting.general], [concept.strictweakorder])

Which strict weak ordering law does this comparator break?

```cpp
struct Pt { int x, y; };

bool comp(const Pt& a, const Pt& b) {
  return a.x < b.x || a.y < b.y;
}
```

A. Irreflexivity: `comp(p, p)` can be true
B. None; it is a valid lexicographic comparison
C. Only transitivity of incomparability
D. Asymmetry: `comp({1, 2}, {2, 1})` and `comp({2, 1}, {1, 2})` are both true

**Answer (D):** Asymmetry: `comp({1, 2}, {2, 1})` and `comp({2, 1}, {1, 2})` are both true

**Why:** With `a = {1, 2}` and `b = {2, 1}`, the first call is true because `1 < 2` on `x`, and the second is true because `1 < 2` on `y`, so each point claims to come before the other. Irreflexivity holds, since neither `p.x < p.x` nor `p.y < p.y` can be true. A real lexicographic comparison only looks at `y` when the `x` values tie, which is what `std::tie(a.x, a.y) < std::tie(b.x, b.y)` does.

### Question 3 [warmup] ([stable.sort], [alg.sorting.general])

What does this program print?

```cpp
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>

struct P { std::string name; int age; };

int main() {
  std::vector<P> ps{{"bo", 30}, {"al", 25}, {"cy", 30}, {"di", 25}};
  std::ranges::stable_sort(ps, {}, &P::age);
  for (auto& p : ps) std::printf("%s ", p.name.c_str());
}
```

A. `al di bo cy `
B. `al bo cy di `
C. `di al cy bo `
D. Any order with the 25s before the 30s

**Answer (A):** `al di bo cy `

**Why:** The projection makes the algorithm compare ages only, so `al` and `di` are equivalent, as are `bo` and `cy`. `stable_sort` keeps equivalent elements in their original relative order: `al` came before `di` and `bo` before `cy`. The last option describes `std::ranges::sort`, which makes no promise about the order within a group of equivalent elements.

### Question 4 [tricky] ([associative.reqmts.general], [alg.find])

What does this program print?

```cpp
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <set>
#include <string>

struct CaseLess {
  bool operator()(const std::string& a, const std::string& b) const {
    auto lower = [](unsigned char c) { return std::tolower(c); };
    return std::ranges::lexicographical_compare(a, b, {}, lower, lower);
  }
};

int main() {
  std::set<std::string, CaseLess> s{"Apple"};
  std::string key = "APPLE";
  bool a = s.contains(key);
  bool b = std::ranges::find(s, key) != s.end();
  std::printf("%d %d\n", a, b);
}
```

A. `1 1`
B. `0 0`
C. `1 0`
D. `0 1`

**Answer (C):** `1 0`

**Why:** `contains` searches the tree with the container's comparator, so it finds the element equivalent to `"APPLE"`. `std::ranges::find` knows nothing about the set's ordering and compares each element with `==`, and `"Apple" == "APPLE"` is false. The two answers disagree because one uses equivalence and the other equality.

### Question 5 [tricky] ([cmp.alg], [alg.sorting.general])

`v` is a `std::vector<double>` that may contain NaN. Which comparator makes `std::sort(v.begin(), v.end(), comp)` well-defined for every possible content of `v`?

A. `[](double a, double b) { return a < b; }`
B. `[](double a, double b) { return !(a >= b); }`
C. `[](double a, double b) { return std::partial_order(a, b) < 0; }`
D. `[](double a, double b) { return std::strong_order(a, b) < 0; }`

**Answer (D):** `[](double a, double b) { return std::strong_order(a, b) < 0; }`

**Why:** `std::strong_order` on IEEE floating-point types implements a total order over all values, including NaNs and signed zeros, so it is a strict weak ordering on any input. `a < b` and `std::partial_order(a, b) < 0` are the same relation, under which NaN is incomparable with everything, which breaks transitivity of incomparability. `!(a >= b)` is true in both directions when either operand is NaN, which breaks asymmetry, and for NaN against itself it breaks irreflexivity too.

### Question 6 [tricky] ([concept.strictweakorder], [concepts.equality])

What happens when this translation unit is compiled?

```cpp
#include <concepts>
#include <functional>

static_assert(std::strict_weak_order<std::ranges::less, int, int>);        // 1
static_assert(std::strict_weak_order<std::ranges::less_equal, int, int>);  // 2
```

A. Both assertions pass
B. Assertion 2 fails because `<=` is reflexive
C. Assertion 2 fails because `less_equal` is not a `relation`
D. It is ill-formed, no diagnostic required, and the compiler rejects it

**Answer (A):** Both assertions pass

**Why:** `strict_weak_order<R, T, U>` is defined as `relation<R, T, U>`: the irreflexivity and transitivity laws are semantic requirements that the compiler cannot check. `ranges::less_equal` is a predicate callable with two `int`s, so it satisfies the concept and the assertion passes. Passing it to `std::ranges::sort` would compile too, while still breaking the requirement the concept documents.

### Question 7 [standardese] ([associative.reqmts.general], [alg.sorting.general])

Given a set `s` with comparator `comp`, which element does `s.find(k)` locate according to the standard?

A. An element `e` with `e == k`
B. An element `e` with `!comp(e, k) && !comp(k, e)`
C. An element `e` with `!comp(k, e)`
D. The first element `e` with `!comp(e, k)`

**Answer (B):** An element `e` with `!comp(e, k) && !comp(k, e)`

**Why:** Associative containers look up keys by equivalence, which [alg.sorting.general] defines as `!comp(a, b) && !comp(b, a)`; `operator==` is never used, so a set with a case-insensitive comparator finds keys that are not equal. `!comp(k, e)` alone accepts any element that is not greater than `k`, and the first `e` with `!comp(e, k)` is what `lower_bound` returns, which may be greater than `k`. Only the two-sided test identifies an equivalent key.

### Question 8 [standardese] ([associative.reqmts.general], [res.on.functions])

What does the standard say about this program?

```cpp
#include <functional>
#include <set>

int main() {
  std::set<int, std::less_equal<int>> s;
  s.insert(1);
  s.insert(1);
  return static_cast<int>(s.size());
}
```

A. It is ill-formed: `std::less_equal` does not meet the requirements of `Compare`, so the declaration is rejected
B. It is well-defined and returns 2, because the keys are never equivalent
C. It is well-defined and returns 1
D. It has undefined behavior

**Answer (D):** It has undefined behavior

**Why:** [associative.reqmts.general] requires the comparator of an associative container to induce a strict weak ordering on the keys, and `<=` is not irreflexive. Breaking a requirement on a user-supplied template argument is undefined behavior by [res.on.functions], so no outcome is guaranteed. Mainstream implementations will happily store two 1s, which makes the second option tempting, but that is an observation about implementations, not a guarantee. Nothing in the type system checks the semantics, so the program does compile.

# Customization points and niebloids

> Generic code needs a way to call "the right swap" or "the right begin" for a type it has never seen. C++ moved from the ADL two-step to customization point objects and niebloids, function objects that do the lookup for you and cannot be hijacked by it, and settled on hidden friends as the way for types to plug in.

- **Source:** C++ Atlas (https://cppatlas.com/topics/customization-points-and-niebloids)
- **Track:** Iterators, algorithms and ranges
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [basic.lookup.argdep] (https://eel.is/c++draft/basic.lookup.argdep), [customization.point.object] (https://eel.is/c++draft/customization.point.object), [concept.swappable] (https://eel.is/c++draft/concept.swappable), [range.access.begin] (https://eel.is/c++draft/range.access.begin), [algorithms.requirements] (https://eel.is/c++draft/algorithms.requirements), [hidden.friends] (https://eel.is/c++draft/hidden.friends), [namespace.std] (https://eel.is/c++draft/namespace.std)
- **cppreference links:** [Customization point object](https://en.cppreference.com/w/cpp/ranges/cpo), [std::ranges::swap](https://en.cppreference.com/w/cpp/utility/ranges/swap), [std::ranges::begin](https://en.cppreference.com/w/cpp/ranges/begin), [Constrained algorithms (algorithm function objects)](https://en.cppreference.com/w/cpp/algorithm/ranges), [Argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl), [Extending the namespace std](https://en.cppreference.com/w/cpp/language/extending_std)
- **Prerequisites:** name-lookup-and-adl, concepts-and-constraints, template-instantiation-and-specialization

## The one idea

A library function such as `sort` has to swap elements of a type it knows nothing about. The type's author may have written a fast `swap`, or may have written nothing, in which case three moves will do. Somebody has to decide which to call, and the decision must happen where the type's author can influence it without editing the library.

For twenty years the answer was argument-dependent lookup, used through an idiom every caller had to remember. C++20 moved the idiom into the library: `std::ranges::swap`, `std::ranges::begin` and their relatives are **customization point objects**, constant function objects whose call operator performs the right lookup, checks the result, and falls back sensibly. The constrained algorithms in `std::ranges` are function objects for a related reason: an object found by ordinary lookup switches ADL off.

> **Mental model.** A customization point object is the two-step idiom written once, correctly, inside the library. You call it with a qualified name; it does the unqualified, ADL-only call on your behalf.

How ADL decides which namespaces to search is covered in the name-lookup-and-adl topic. Here the question is how libraries use it.

## The ADL two-step and how it fails

The classic idiom brings `std::swap` into scope as a fallback and then makes an unqualified call, so ADL can find a better `swap` in the argument's namespace.

```cpp
#include <cstdio>
#include <utility>

namespace lib {
  struct Widget {
    int id;
    friend void swap(Widget& a, Widget& b) noexcept {
      std::puts("lib swap");
      std::swap(a.id, b.id);
    }
  };
}

template <class T> void good(T& a, T& b) { using std::swap; swap(a, b); }
template <class T> void bad(T& a, T& b) { std::swap(a, b); }

int main() {
  lib::Widget a{1}, b{2};
  good(a, b);  // prints lib swap
  bad(a, b);   // prints nothing: generic std::swap, three moves
}
```

Every part of the idiom can go wrong, and every failure compiles.

- **Qualifying the call.** `std::swap(a, b)` suppresses ADL, so the type's own `swap` is silently skipped. The code is correct but may be slow, or may lose an invariant the custom `swap` preserved.
- **Forgetting the using-declaration.** Without `using std::swap;`, the unqualified call finds nothing for `int` or for types without their own `swap`, and generic code breaks only for some instantiations.
- **No constraints.** Nothing checks that the function ADL found actually swaps, or that a `begin` found the same way returns an iterator.
- **Hijacking.** ADL searches every namespace associated with the argument types, including those of template arguments. An unconstrained function template with the right name in any of those namespaces can be a better match than the one you meant, or make the call ambiguous.

## Customization point objects

A customization point object, as [customization.point.object] describes it, is a constant function object of a literal, semiregular type. Its call operator is constrained, so a failed customization is a substitution failure rather than a hard error. Each one tries a fixed sequence of strategies and takes the first that is valid.

`std::ranges::swap(t, u)`, specified in [concept.swappable], tries:

1. An unqualified `swap(t, u)` when either argument has class or enumeration type, with overload resolution performed in a context that also sees a deleted `template<class T> void swap(T&, T&)`. That deleted candidate makes the unconstrained `std::swap` lose to an ambiguity, so only a genuine customization is chosen. If the function found does not exchange the values, the program is ill-formed, no diagnostic required.
2. Otherwise, for two lvalue arrays of equal extent, `ranges::swap_ranges`.
3. Otherwise, for two lvalues of the same move-constructible and move-assignable type, an exchange through moves, with a `noexcept` computed from the type.

`std::ranges::begin(t)` checks an array first, then a member `t.begin()`, then an ADL-only `begin(t)`, and in each case requires the result to model `input_or_output_iterator`. It also refuses an rvalue argument unless the type is a borrowed range, which the borrowed-ranges-and-dangling topic explains. `ranges::size` goes array extent, member `size()`, ADL `size()`, and finally `end - begin` for sized sentinels.

```cpp
#include <ranges>

namespace lib {
  struct Bag { int data[3]{1, 2, 3}; };
  int* begin(Bag& b) { return b.data; }   // found by ADL
  int* end(Bag& b) { return b.data + 3; }

  struct Both {
    int d[2]{};
    int* begin() { return d; }            // member wins
    int* end() { return d + 2; }
  };
  int* begin(Both&) = delete;             // never considered
}

static_assert(std::ranges::range<lib::Bag>);
static_assert(std::ranges::range<lib::Both>);
static_assert(!std::ranges::range<const lib::Bag>);  // no const overloads
```

C++20 originally specified deleted "poison pill" overloads for `begin`, `end`, `size` and their relatives as well. The defect report P2602 replaced those with a plain requirement that the lookup be argument-dependent only, which is how the C++23 wording reads.

> **Standardese.** [customization.point.object] says all instances of a customization point object's type are equal, and the effect of calling one does not depend on whether the object expression is an lvalue or an rvalue, const or not. That is what makes it safe to copy a CPO into an algorithm, or to call it through a reference.

## Why objects, and what niebloids are

Being an object matters for two reasons. The first is that an object can be passed around: `std::ranges::transform(vs, out, std::ranges::size)` works, while taking the address of most standard functions is unspecified since C++20. The second is about lookup. [basic.lookup.argdep] says that if ordinary unqualified lookup finds something that is not a function or function template, such as a variable, ADL is not performed at all. A CPO in scope therefore cannot be supplemented or hijacked by ADL, so `using std::ranges::swap; swap(a, b);` simply calls the object, which then does its own careful lookup internally.

The constrained algorithms, `std::ranges::sort`, `std::ranges::find` and the rest, rely on the same property. Eric Niebler's range-v3 library implemented them as function objects so they behave like this, and they acquired his name: **niebloids**. [algorithms.requirements] in C++20 and C++23 states the effect without demanding an implementation technique: these entities are not found by ADL, and when found by unqualified lookup they inhibit ADL. C++26, through P3136, specifies them directly as algorithm function objects.

```cpp
#include <algorithm>
#include <cstdio>
#include <vector>

namespace lib {
  struct Rec { int v; bool operator==(const Rec&) const = default; };
  template <class It, class T> It find(It, It last, const T&) { return last; }
}

void f(std::vector<lib::Rec>& v) {
  using std::ranges::find;
  auto it = find(v.begin(), v.end(), lib::Rec{1});  // std::ranges::find, ADL off
  (void)it;
  // With 'using std::find;' instead, ADL adds lib::find (lib is associated
  // through vector<lib::Rec>), and the call is ambiguous.
}
```

> **Pitfall.** A niebloid's constraints are stricter than the old algorithm's. `std::ranges::find` requires the element and the value to be comparable with `==` in the sense of `indirect_binary_predicate`, so code that compiled with `std::find` can fail with the `ranges` version until the types are fixed.

## tag_invoke, and why it was left behind

CPOs solved calling, but defining a new CPO meant reserving a new global name for ADL to search, such as `swap`, `begin`, `iter_move`. The tag_invoke proposal, P1895, generalized this: every customization goes through one ADL name, `tag_invoke`, and the CPO object itself is passed as the first argument to say which operation is meant.

```cpp
#include <type_traits>
#include <utility>

namespace my {
  struct tag_invoke_fn {
    template <class Tag, class... Args>
    constexpr auto operator()(Tag t, Args&&... args) const
        -> decltype(tag_invoke(t, std::forward<Args>(args)...)) {
      return tag_invoke(t, std::forward<Args>(args)...);
    }
  };
  inline constexpr tag_invoke_fn tag_invoke_cpo{};

  inline constexpr struct get_name_fn {
    template <class T>
    constexpr auto operator()(const T& t) const -> decltype(tag_invoke_cpo(*this, t)) {
      return tag_invoke_cpo(*this, t);
    }
  } get_name{};
}

struct Dog {
  friend const char* tag_invoke(decltype(my::get_name), const Dog&) { return "dog"; }
};

inline const char* dog_name() { return my::get_name(Dog{}); }  // "dog"
```

It works, and libraries such as libunifex and early drafts of `std::execution` used it widely. It was not adopted into the standard. Every customization of every operation joins one overload set named `tag_invoke`, which hurts compile times and produces error messages that list every candidate in sight. The definitions are hard to read and to search for. When `std::execution` was finalized for C++26 (P2300, revised by P2855), its customizations moved to member functions and environment queries instead. A language feature for customizable functions has been proposed and has not been adopted.

## How to customize today

For your own types, provide the operation as a **hidden friend**: a friend function defined inside the class. It lives in the enclosing namespace but is invisible to ordinary lookup, so only ADL with an argument of your type can find it. [hidden.friends] specifies that the friend functions the standard library itself declares inside its classes are hidden friends in exactly this sense.

```cpp
#include <cstdio>

namespace geo {
  struct Meters {
    double v;
    Meters(double d) : v(d) {}
    friend void print(Meters m) { std::printf("%g m\n", m.v); }
  };
}

int main() {
  geo::Meters m{2.0};
  print(m);         // OK: found by ADL
  // print(3.0);    // error: no argument of type Meters, so no ADL into geo
  // geo::print(m); // error: qualified lookup cannot see a hidden friend
}
```

Hidden friends keep overload sets small, avoid accidental conversions from unrelated types, and make compile errors shorter. Customization point objects find them, which is all most types need: a hidden `swap`, `begin` and `end`, `iter_move` and `iter_swap` for iterators.

Some customization still happens by specializing templates in `std`, and [namespace.std] limits it tightly.

- A **class template** may be specialized if the specialization depends on a program-defined type and meets the original's requirements: `std::hash`, `std::formatter`, `std::tuple_size`, `std::common_type`, `std::basic_common_reference`.
- The type traits in `<type_traits>` may not be specialized, apart from `common_type` and `basic_common_reference`. Specializing `std::is_integral` for your type is undefined behavior.
- A **variable template** may be specialized only where the standard says so, as for `std::ranges::enable_borrowed_range`, `enable_view`, `disable_sized_range` and `std::disable_sized_sentinel_for`.
- **Function templates** may no longer be specialized since C++20 (P0551). `template<> void std::swap(Widget&, Widget&)` was allowed before and is undefined behavior now. Adding overloads to `std` was never allowed.

## What to remember

- The two-step `using std::swap; swap(a, b);` works, but qualifying the call or forgetting the using-declaration silently does the wrong thing.
- Customization point objects perform the two-step for you, constrain the result, and fall back in a fixed order.
- `ranges::begin` tries array, member, then ADL; `ranges::swap` tries ADL `swap`, then arrays, then moves.
- Ordinary lookup finding an object disables ADL, so CPOs and niebloids cannot be hijacked.
- The `std::ranges` algorithms are niebloids: never found by ADL, and they inhibit it when found by unqualified lookup.
- `tag_invoke` funnelled all customization through one name and was dropped; C++26 `std::execution` uses members and queries.
- Customize with hidden friends; only ADL can find them.
- Specialize `std` class templates only for your own types, never type traits, and never function templates since C++20.

## Concept Map Outline

- **Customization points:** How generic code calls the right operation for a type it has never seen.
  - **ADL two-step:** using std::swap; swap(a, b); lets ADL find a better swap, with std::swap as fallback.
    - **Qualified call:** std::swap(a, b) suppresses ADL and silently skips the type's own swap.
    - **Missing using:** Without the using-declaration, ints and types lacking swap fail to compile.
    - **Hijacking:** Any same-named template in an associated namespace can win or cause ambiguity.
  - **CPOs:** Const semiregular function objects that do the lookup, check it, and fall back.
    - **ranges::swap order:** ADL swap with a deleted swap(T&, T&) candidate, then equal-extent arrays, then moves.
    - **ranges::begin order:** Array, then member begin(), then ADL-only begin(); result must be an iterator.
    - **ranges::size order:** Array extent, member size(), ADL size(), then end minus begin for sized sentinels.
    - **P2602 cleanup:** Defect report against C++20 replaced poison pills for begin, end, size with ADL-only wording.
  - **Why objects:** Objects can be passed around and are immune to ADL.
    - **ADL suppression:** If unqualified lookup finds a variable, [basic.lookup.argdep] performs no ADL.
    - **Passable:** ranges::size can be an algorithm argument; most std functions cannot be addressed.
    - **All instances equal:** Calling a CPO does not depend on the object's value category or constness.
  - **Niebloids:** The std::ranges algorithms, named after Eric Niebler's range-v3 technique.
    - **C++20 and C++23:** Not found by ADL, and they inhibit ADL when found by unqualified lookup.
    - **C++26:** P3136 specifies them directly as algorithm function objects.
    - **Stricter constraints:** ranges::find needs indirect_binary_predicate; some std::find calls do not port.
  - **tag_invoke:** P1895: one ADL name for all customizations, with the CPO passed as a tag.
    - **Costs:** One giant overload set: slow compiles, long errors, hard-to-read definitions.
    - **Not adopted:** C++26 std::execution moved to member functions and environment queries.
  - **Customizing today:** Hidden friends for operations; narrow rules for specializing std templates.
    - **Hidden friends:** Defined in the class, found only by ADL; no conversions from unrelated types.
    - **Class templates:** Specialize hash, formatter, tuple_size for program-defined types only.
    - **Type traits:** Specializing <type_traits> templates is UB except common_type and basic_common_reference.
    - **Function templates:** Specializing them is undefined behavior since C++20 (P0551).

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.lookup.argdep], [utility.swap])

What does this program print?

```cpp
#include <cstdio>
#include <utility>

namespace lib {
  struct Widget {
    int id;
    friend void swap(Widget& a, Widget& b) noexcept {
      std::puts("lib swap");
      std::swap(a.id, b.id);
    }
  };
}

template <class T> void exchange_them(T& a, T& b) { std::swap(a, b); }

int main() {
  lib::Widget a{1}, b{2};
  exchange_them(a, b);
}
```

A. `lib swap`
B. Nothing
C. `lib swap` twice
D. It is ill-formed: the call is ambiguous

**Answer (B):** Nothing

**Why:** A qualified call `std::swap(a, b)` performs no argument-dependent lookup, so the hidden friend in `lib` is never a candidate. The generic `std::swap` template exchanges the values with one move construction and two move assignments, printing nothing. To reach the custom `swap`, write `using std::swap; swap(a, b);` or call `std::ranges::swap(a, b)`.

### Question 2 [warmup] ([hidden.friends], [basic.lookup.argdep], [namespace.memdef])

Which statement about the two marked calls is true?

```cpp
#include <cstdio>

namespace geo {
  struct Meters {
    double v;
    Meters(double d) : v(d) {}
    friend void print(Meters m) { std::printf("%g m\n", m.v); }
  };
}

int main() {
  geo::Meters m{2.0};
  print(m);    // 1
  print(3.0);  // 2
}
```

A. Both compile; call 2 converts `3.0` to `Meters`
B. Call 1 is ill-formed because `print` is not declared at namespace scope
C. Call 2 is ill-formed: no argument has type `Meters`, so ADL never looks inside `geo`
D. Both are ill-formed, because a friend function cannot be called without qualification

**Answer (C):** Call 2 is ill-formed: no argument has type `Meters`, so ADL never looks inside `geo`

**Why:** A friend defined only inside a class is a hidden friend: it belongs to `geo` but ordinary lookup cannot find it, and only argument-dependent lookup triggered by an argument of type `Meters` can. Call 1 has such an argument, so it works. Call 2 passes a `double`, which has no associated namespaces, so the name is not found at all and the implicit conversion is never considered. That is a deliberate benefit of hidden friends.

### Question 3 [warmup] ([basic.lookup.argdep], [concept.swappable], [customization.point.object])

What does this program print?

```cpp
#include <concepts>
#include <cstdio>
#include <utility>

namespace lib {
  struct Widget {
    int id;
    friend void swap(Widget& a, Widget& b) noexcept {
      std::puts("lib swap");
      std::swap(a.id, b.id);
    }
  };
}

int main() {
  lib::Widget a{1}, b{2};
  using std::ranges::swap;
  swap(a, b);
}
```

A. `lib swap`
B. Nothing: the using-declaration names an object, so ADL is switched off and `lib::swap` is never called
C. `lib swap` twice
D. It is ill-formed: the call is ambiguous between the object and the friend

**Answer (A):** `lib swap`

**Why:** Ordinary lookup finds the object `std::ranges::swap`, and because it is not a function, ADL is not performed for this call, so there is no ambiguity. The object's call operator then performs its own unqualified, ADL-based lookup for `swap(t, u)`, which finds the hidden friend and prints once. The second option is right that ADL is suppressed at the call site, but misses that the customization point object does the lookup internally.

### Question 4 [tricky] ([basic.lookup.argdep], [over.match.best], [algorithms.requirements])

What happens with the call to `find`?

```cpp
#include <algorithm>
#include <vector>

namespace lib {
  struct Rec { int v; bool operator==(const Rec&) const = default; };
  template <class It, class T> It find(It, It last, const T&) { return last; }
}

void f(std::vector<lib::Rec>& v) {
  using std::find;
  find(v.begin(), v.end(), lib::Rec{1});
}
```

A. It calls `std::find`, because the using-declaration takes priority
B. It calls `lib::find`, because ADL results are preferred
C. It calls `std::ranges::find`
D. It is ill-formed: the call is ambiguous between `std::find` and `lib::find`

**Answer (D):** It is ill-formed: the call is ambiguous between `std::find` and `lib::find`

**Why:** `std::find` is a function template, so ADL still runs, and `lib` is an associated namespace through the template argument `lib::Rec` of the vector's iterator type. Both templates have the same parameter pattern, neither is more specialized, and the call is ambiguous. Had the using-declaration named the niebloid `std::ranges::find`, ordinary lookup would find an object, ADL would be suppressed, and the call would be unambiguous.

### Question 5 [tricky] ([range.access.begin], [range.access.end], [range.range])

Does this compile?

```cpp
#include <ranges>

namespace lib {
  struct Both {
    int d[2]{};
    int* begin() { return d; }
    int* end() { return d + 2; }
  };
  int* begin(Both&) = delete;
  int* end(Both&) = delete;
}

static_assert(std::ranges::range<lib::Both>);
```

A. Yes: `ranges::begin` and `ranges::end` use the members and never reach the ADL step
B. No: ADL finds the deleted functions, which makes `ranges::begin` ill-formed
C. No: the member and the free function make the call ambiguous
D. Yes, but only because deleted functions are ignored by overload resolution

**Answer (A):** Yes: `ranges::begin` and `ranges::end` use the members and never reach the ADL step

**Why:** `ranges::begin` tries its strategies in order: array, then a valid member `t.begin()` returning an iterator, then ADL-only `begin(t)`. The member is valid here, so the deleted free functions are never looked at. The last option is wrong on its own terms: deleted functions do take part in overload resolution, and selecting one makes the expression invalid, which is exactly what would happen if there were no members.

### Question 6 [tricky] ([concept.swappable], [customization.point.object])

What happens with this call?

```cpp
#include <concepts>

int main() {
  int x[2]{1, 2}, y[3]{3, 4, 5};
  std::ranges::swap(x, y);
}
```

A. It swaps the first two elements and leaves `y[2]` alone
B. It is ill-formed: no strategy of `ranges::swap` applies
C. It compiles but has undefined behavior
D. It swaps what the two names refer to

**Answer (B):** It is ill-formed: no strategy of `ranges::swap` applies

**Why:** `ranges::swap` tries an ADL `swap`, which needs a class or enumeration argument; then `swap_ranges` for lvalue arrays of equal extent; then a move-based exchange of two lvalues of the same movable type. `int[2]` and `int[3]` fail all three, so the call operator is not viable and the call does not compile. Arrays are never swapped partially.

### Question 7 [standardese] ([namespace.std])

In C++20 and later, what is the status of this explicit specialization?

```cpp
#include <utility>

namespace lib { struct Widget { int id; }; }

template <>
void std::swap<lib::Widget>(lib::Widget& a, lib::Widget& b) noexcept {
  std::swap(a.id, b.id);
}
```

A. Allowed, because it depends on a program-defined type
B. Ill-formed: a diagnostic is required
C. Allowed only if it is declared `noexcept`
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** Since C++20 (P0551), [namespace.std] allows programs to specialize standard library class templates for program-defined types, but no longer function templates, so this declaration has undefined behavior. Until C++17 it was permitted, which is why the first option is tempting. Compilers accept it silently; put a hidden friend `swap` in the class instead.

### Question 8 [standardese] ([namespace.std], [meta.rqmts], [range.range])

`MyType` and `MyView` are program-defined types that meet the relevant requirements. Which of these declarations has undefined behavior?

A. `template<> struct std::hash<MyType> { std::size_t operator()(const MyType&) const; };`
B. `template<> struct std::is_integral<MyType> : std::true_type {};`
C. `template<> inline constexpr bool std::ranges::enable_borrowed_range<MyView> = true;`
D. `template<> struct std::tuple_size<MyType> : std::integral_constant<std::size_t, 2> {};`

**Answer (B):** `template<> struct std::is_integral<MyType> : std::true_type {};`

**Why:** [namespace.std] and [meta.rqmts] forbid specializing the templates in `<type_traits>`, with `common_type` and `basic_common_reference` as the only exceptions, so specializing `is_integral` is undefined behavior. `std::hash` is a class template specialized for a program-defined type, which is allowed. `enable_borrowed_range` is one of the variable templates the standard explicitly lets programs specialize for their own types. Specializing `std::tuple_size`, as for structured bindings, is an ordinary class template specialization and is allowed too.

# Iterator adaptors and sentinels

> Iterator adaptors wrap an iterator to change what moving or dereferencing means, and C++20 sentinels let the end of a range be a different type from its iterator. Together they explain reverse_iterator's off-by-one base, counted and common iterators, subrange, and why C++23 had to fix cbegin.

- **Source:** C++ Atlas (https://cppatlas.com/topics/iterator-adaptors-and-sentinels)
- **Track:** Iterators, algorithms and ranges
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [reverse.iterators] (https://eel.is/c++draft/reverse.iterators), [move.iterators] (https://eel.is/c++draft/move.iterators), [insert.iterators] (https://eel.is/c++draft/insert.iterators), [stream.iterators] (https://eel.is/c++draft/stream.iterators), [iterators.counted] (https://eel.is/c++draft/iterators.counted), [iterators.common] (https://eel.is/c++draft/iterators.common), [unreachable.sentinel] (https://eel.is/c++draft/unreachable.sentinel), [iterator.concept.sentinel] (https://eel.is/c++draft/iterator.concept.sentinel), [range.subrange] (https://eel.is/c++draft/range.subrange), [const.iterators] (https://eel.is/c++draft/const.iterators), [range.access.cbegin] (https://eel.is/c++draft/range.access.cbegin)
- **cppreference links:** [std::reverse_iterator](https://en.cppreference.com/w/cpp/iterator/reverse_iterator), [std::move_iterator](https://en.cppreference.com/w/cpp/iterator/move_iterator), [std::counted_iterator](https://en.cppreference.com/w/cpp/iterator/counted_iterator), [std::common_iterator](https://en.cppreference.com/w/cpp/iterator/common_iterator), [std::unreachable_sentinel_t](https://en.cppreference.com/w/cpp/iterator/unreachable_sentinel_t), [std::ranges::subrange](https://en.cppreference.com/w/cpp/ranges/subrange), [std::basic_const_iterator](https://en.cppreference.com/w/cpp/iterator/basic_const_iterator)
- **Prerequisites:** iterator-categories-and-concepts, ranges-and-views

## The one idea

An iterator adaptor holds another iterator and redefines one or two of its operations. `reverse_iterator` swaps increment and decrement. `move_iterator` turns each dereference into an rvalue. An insert iterator turns assignment into a container call. `counted_iterator` carries a countdown. None of them owns data; each is a thin rule layered over the iterator inside it.

C++20 added the other half of the picture: the end of a range no longer has to be an iterator. A **sentinel** is any type that can be compared with the iterator to answer "are we done?". That lets a null-terminated string, an unbounded sequence, or "the next five elements" be expressed without computing an end position up front. The cost is that older code, which expects `first` and `last` of the same type, needs an adaptor to bridge the gap.

> **Mental model.** An iterator says where you are; a sentinel only says whether you have arrived. Adaptors change the meaning of moving and reading, and `common_iterator` exists only to make the two halves the same type again.

What each iterator category promises is the subject of the iterator-categories-and-concepts topic; this one assumes it.

## reverse_iterator and the off-by-one base

A reverse iterator stores an ordinary iterator, `base()`, that points one position *after* the element it denotes. `rbegin()` wraps `end()`, and `rend()` wraps `begin()`. Dereferencing a reverse iterator `r` yields `*std::prev(r.base())`. The offset is what makes `rend()` representable: there is no valid position before `begin()`, but there is a valid `begin()` to stand one past the reversed end.

```text
elements:     [1]  [2]  [3]  [4]  [5]
iterators:   b                         e
reverse r:              *r = 3
r.base():                    -> 4
```

```cpp
#include <algorithm>
#include <cstdio>
#include <iterator>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3, 4, 5};
  auto r = std::find(v.rbegin(), v.rend(), 3);
  std::printf("%d %d\n", *r, *r.base());  // prints 3 4
  v.erase(std::next(r).base());            // erases the 3, not the 4
}
```

Converting the other way has the same offset. `std::reverse_iterator(it)` denotes the element *before* `it`, so a reverse iterator built from `v.begin() + 2` dereferences to `v[1]`. To erase through a reverse iterator, step it once and take the base, as above, or the code silently removes the neighbour.

The same offset explains why `reverse_iterator` needs a bidirectional iterator and costs a decrement on every dereference. `views::reverse` uses it too, and for a range that is not common it must first walk to the end to find the position to start from, which is why `reverse_view` caches its `begin()`.

## move_iterator and move_sentinel

A `move_iterator` dereferences to an rvalue reference, `std::ranges::iter_move` of the underlying iterator since C++20. Passing a pair of them to a constructor or algorithm that copies turns the copies into moves.

```cpp
#include <iterator>
#include <string>
#include <vector>

void take_all(std::vector<std::string>& src) {
  std::vector<std::string> dst(std::make_move_iterator(src.begin()),
                               std::make_move_iterator(src.end()));
  // src still has its elements, each in a valid but unspecified state
}
```

The source elements are moved from, not removed. An algorithm that reads an element more than once is dangerous here. `std::copy_if` with a predicate that takes `std::string` by value moves the string into the predicate, then copies what is left into the output.

```cpp
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>

void keep_long(std::vector<std::string>& src, std::vector<std::string>& out) {
  std::copy_if(std::make_move_iterator(src.begin()), std::make_move_iterator(src.end()),
               std::back_inserter(out),
               [](std::string s) { return s.size() > 4; });
  // the predicate already moved each string out; out receives moved-from
  // strings, which libstdc++ leaves empty
}
```

The fix is a predicate that takes `const std::string&`, so testing an element reads it without consuming it. The general rule is that a `move_iterator` range is safe to hand only to algorithms that read each element once.

C++20 added `move_sentinel<S>`, which wraps a sentinel so that a `move_iterator<I>` can be compared with it. In C++20 a `move_iterator` modelled only `input_iterator`; C++23 (P2520) lets it model the underlying category, up to random access.

## Insert and stream iterators

Insert iterators adapt a container, not an iterator. Assigning to one calls `push_back`, `push_front` or `insert`; `*it` and `++it` do nothing and return the iterator itself. `std::back_inserter(c)` appends in order. `std::front_inserter(c)` reverses the sequence, since each element goes in front of the last one. `std::inserter(c, pos)` inserts before `pos` and then advances its stored position past the new element, so a run of values lands in order. Since C++20 they have `std::ptrdiff_t` as `difference_type` instead of `void`, which lets them model `std::output_iterator` for the constrained algorithms.

```cpp
#include <algorithm>
#include <deque>
#include <iterator>
#include <list>
#include <vector>

void fill() {
  std::deque<int> d;
  std::ranges::copy(std::vector{1, 2, 3}, std::front_inserter(d));  // d: 3 2 1
  std::list<int> l{10, 20};
  std::ranges::copy(std::vector{1, 2, 3}, std::inserter(l, std::next(l.begin())));
  // l: 10 1 2 3 20
}
```

Stream iterators adapt a stream. `std::istream_iterator<T>` reads with `>>`, and it reads the first value in its constructor, so creating one consumes input even if you never dereference it. A default-constructed one is the end-of-stream iterator, and an iterator becomes equal to it when extraction fails. `std::ostream_iterator<T>(os, delim)` writes each value followed by the delimiter, so the output ends with a trailing delimiter. `istreambuf_iterator` and `ostreambuf_iterator` work on raw characters with no formatting and no skipping of whitespace.

## Sentinels, iterator_t and sentinel_t

`std::sentinel_for<S, I>` requires `S` to be semiregular and comparable with `I` through `==` and `!=`. Thanks to C++20's rewritten comparisons, one `operator==` taking the iterator and the sentinel is enough.

```cpp
#include <iterator>
#include <ranges>

struct NullTerm {
  friend bool operator==(const char* p, NullTerm) { return *p == '\0'; }
};
static_assert(std::sentinel_for<NullTerm, const char*>);

auto n = std::ranges::distance("hello", NullTerm{});  // 5, no strlen up front
```

For a range type `R`, `std::ranges::iterator_t<R>` is the type `ranges::begin` returns for an lvalue `R`, and `std::ranges::sentinel_t<R>` is what `ranges::end` returns. `common_range<R>` means exactly that the two are the same type. Note that `iterator_t<const R>` is a separate question: it is `const_iterator` for a vector, and it does not exist at all for a `filter_view`.

`std::unreachable_sentinel` compares unequal to every iterator. `views::iota(0)` uses it to be infinite, and an algorithm such as `std::ranges::find(it, std::unreachable_sentinel, x)` drops its bounds check when you already know `x` is present. If it is not, the search runs off the end, which is undefined behaviour.

`std::ranges::subrange<I, S>` packages an iterator and a sentinel as a view. It is what `ranges::equal_range` and friends return, it is always a borrowed range, and it supports structured bindings: `auto [first, last] = std::ranges::subrange(v);`. When `I` and `S` cannot compute a distance, a subrange can store a size alongside them so that it remains sized.

## counted_iterator and default_sentinel

`std::counted_iterator<I>` pairs an iterator with a remaining count. Incrementing it decrements the count, and it compares equal to `std::default_sentinel` when the count reaches zero, independently of the underlying sequence. That makes "the next `n` elements" a sized range even for a list or an input stream, and it never steps past the last element it needs.

```cpp
#include <iterator>
#include <list>
#include <ranges>
#include <span>
#include <type_traits>
#include <vector>

std::list<int> l{1, 2, 3, 4};
std::vector<int> v{1, 2, 3, 4};
auto a = std::views::counted(l.begin(), 2);
auto b = std::views::counted(v.begin(), 2);
static_assert(std::is_same_v<decltype(a),
    std::ranges::subrange<std::counted_iterator<std::list<int>::iterator>,
                          std::default_sentinel_t>>);
static_assert(std::is_same_v<decltype(b), std::span<int>>);
```

`views::counted` picks the cheapest representation: a `std::span` for contiguous iterators, a plain `subrange(it, it + n)` for other random-access iterators, and a counted iterator with `default_sentinel` otherwise. `views::take` uses the same machinery when its input is not random access. Two counted iterators over the same sequence can be subtracted by comparing their counts, so the distance is O(1) even when the underlying iterator cannot provide it.

> **Pitfall.** `views::counted(it, n)` trusts you. If fewer than `n` elements follow `it`, iterating the view runs past the end of the underlying sequence, and the behaviour is undefined.

## common_iterator and views::common

Code written before C++20, including the iterator-pair constructors of every container, needs `first` and `last` of one type. `std::common_iterator<I, S>` holds either an `I` or an `S` and compares them correctly, and `views::common` uses it to turn any range into a common one. It requires `I` to be copyable, so it cannot help a move-only input iterator.

```cpp
#include <ranges>
#include <vector>

void build() {
  auto r = std::views::iota(0) | std::views::take(5);
  // std::vector<int> a(r.begin(), r.end());  // error: different types
  auto c = r | std::views::common;
  std::vector<int> b(c.begin(), c.end());     // OK
  auto d = std::ranges::to<std::vector>(r);   // C++23: no adaptor needed
  (void)b; (void)d;
}
```

C++23 makes the bridge less necessary: `std::ranges::to` and the containers' `from_range` constructors accept any range directly.

## Const iterators and the C++23 cbegin fix

In C++20, `std::ranges::cbegin(r)` meant `ranges::begin` applied to `r` as const. For a container that gives a const iterator, but a view such as `std::span<int>` has shallow constness: its const `begin()` still returns a mutable iterator. So C++20's `cbegin` on a span let you write through it.

C++23 (P2278) fixed the ranges version. `std::ranges::cbegin` now returns `std::const_iterator<I>`, which is `I` itself if it already yields const references and `std::basic_const_iterator<I>` otherwise. `views::as_const` and the alias `std::ranges::const_iterator_t<R>` came with it. The non-member `std::cbegin` from `<iterator>` was not changed, and still returns a mutable iterator for a span.

```cpp
#include <iterator>
#include <ranges>
#include <span>
#include <type_traits>
#include <vector>

std::vector<int> v{1, 2, 3};
std::span<int> sp(v);
static_assert(std::is_same_v<decltype(*std::ranges::cbegin(sp)), const int&>);  // C++23
static_assert(std::is_same_v<decltype(*std::cbegin(sp)), int&>);  // still mutable
```

> **Standardese.** [range.access.cbegin] in C++23 defines `ranges::cbegin(E)` through `const_iterator<decltype(U)>` built from `ranges::begin` of a possibly const view of `E`, and [const.iterators] specifies `basic_const_iterator` as an adaptor whose reference type is the iterator's const reference type. The guarantee is about the type, so writing through it is ill-formed rather than undefined.

## What to remember

- A reverse iterator's `base()` points one past the element it denotes; erase with `std::next(r).base()`.
- `move_iterator` dereferences to an rvalue, so any algorithm that reads twice sees a moved-from value.
- `front_inserter` reverses order; `inserter` keeps order by advancing its position after each insert.
- `istream_iterator` reads its first value in the constructor; `ostream_iterator` writes a trailing delimiter.
- A sentinel only answers "done?"; `common_range` means `iterator_t` and `sentinel_t` are the same type.
- `unreachable_sentinel` removes bounds checks; if the value is missing, that is undefined behaviour.
- `views::counted` yields a span, a subrange, or a `counted_iterator` with `default_sentinel`, by iterator category.
- `views::common` bridges to pre-C++20 code; in C++23 prefer `ranges::to`.
- C++23 `ranges::cbegin` always yields a const iterator; `std::cbegin` on a span is still mutable.

## Concept Map Outline

- **Iterator adaptors and sentinels:** Wrappers that redefine moving or reading, and ends that need not be iterators.
  - **reverse_iterator:** Swaps increment and decrement; needs a bidirectional iterator.
    - **Off-by-one base:** base() points one past the element: *r is *std::prev(r.base()).
    - **Erasing:** Erase through r with v.erase(std::next(r).base()), or the neighbour goes.
    - **From an iterator:** reverse_iterator(it) denotes the element before it.
  - **Moving and inserting:** Adaptors that change what dereference or assignment does.
    - **move_iterator:** Dereferences to an rvalue via iter_move; algorithms that read twice see moved-from values.
    - **move_sentinel:** C++20 wrapper letting a move_iterator compare with a sentinel.
    - **Insert iterators:** Assignment calls push_back, push_front or insert; front_inserter reverses order.
    - **Stream iterators:** istream_iterator reads in its constructor; ostream_iterator writes a trailing delimiter.
  - **Sentinels:** A type that only answers whether iteration is done.
    - **sentinel_for:** Semiregular and ==-comparable with the iterator; one operator== suffices in C++20.
    - **iterator_t, sentinel_t:** Types of ranges::begin and ranges::end; common_range means they are the same.
    - **unreachable_sentinel:** Never equal to any iterator; drops bounds checks, UB if the value is absent.
    - **subrange:** Iterator plus sentinel as a borrowed view, with structured bindings.
  - **counted_iterator:** An iterator with a countdown, done when the count reaches zero.
    - **default_sentinel:** Compares equal to a counted_iterator whose count is zero.
    - **views::counted:** span if contiguous, subrange(it, it + n) if random access, else counted_iterator.
    - **Trusts the count:** Fewer than n elements after it means undefined behavior.
  - **common_iterator:** Holds an iterator or a sentinel so both ends share one type.
    - **views::common:** Makes any range common for pre-C++20 iterator-pair APIs; needs a copyable iterator.
    - **C++23 alternative:** ranges::to and from_range constructors accept any range directly.
  - **Const iterators:** C++23 (P2278) made ranges::cbegin genuinely const.
    - **basic_const_iterator:** Adaptor whose dereference yields the const reference type.
    - **ranges::cbegin fix:** On a span it now yields const int&; in C++20 it was writable.
    - **std::cbegin unchanged:** Non-member std::cbegin on a span still returns a mutable iterator.

## Standardese Quiz Questions

### Question 1 [warmup] ([reverse.iterators])

What does this program print?

```cpp
#include <algorithm>
#include <cstdio>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3, 4, 5};
  auto r = std::find(v.rbegin(), v.rend(), 3);
  std::printf("%d %d\n", *r, *r.base());
}
```

A. `3 3`
B. `3 2`
C. `3 4`
D. Undefined behavior: `base()` of a reverse iterator must not be dereferenced

**Answer (C):** `3 4`

**Why:** A reverse iterator stores a base iterator one position after the element it denotes, and dereferencing it yields `*std::prev(base())`. The reverse iterator that finds 3 therefore has a base pointing at 4. Dereferencing `base()` is fine here because it points at a real element; it would only be undefined for the reverse iterator equal to `rbegin()`, whose base is `end()`.

### Question 2 [warmup] ([front.insert.iterator], [insert.iterators])

What does this program print?

```cpp
#include <algorithm>
#include <cstdio>
#include <deque>
#include <iterator>
#include <vector>

int main() {
  std::deque<int> d{0};
  std::vector<int> src{1, 2, 3};
  std::copy(src.begin(), src.end(), std::front_inserter(d));
  for (int x : d) std::printf("%d ", x);
}
```

A. `1 2 3 0 `
B. `3 2 1 0 `
C. `0 1 2 3 `
D. `0 3 2 1 `

**Answer (B):** `3 2 1 0 `

**Why:** Each assignment through a `front_insert_iterator` calls `push_front`, so 1 goes in front of 0, then 2 in front of 1, then 3 in front of 2. The copied sequence ends up reversed, ahead of the existing element. `1 2 3 0 ` is what `std::inserter(d, d.begin())` would give, because an insert iterator advances its position past each element it inserts.

### Question 3 [warmup] ([ostream.iterator.ops])

What does this program print, between the brackets?

```cpp
#include <algorithm>
#include <cstdio>
#include <iterator>
#include <sstream>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3};
  std::ostringstream os;
  std::copy(v.begin(), v.end(), std::ostream_iterator<int>(os, ", "));
  std::printf("[%s]\n", os.str().c_str());
}
```

A. `[1, 2, 3]`
B. `[, 1, 2, 3]`
C. `[123]`
D. `[1, 2, 3, ]`

**Answer (D):** `[1, 2, 3, ]`

**Why:** `ostream_iterator` writes the delimiter after every value it is assigned, including the last, so the output has a trailing `, `. It is not a joiner and has no idea which value is the last one. To avoid the trailing separator, write the first element separately, or in C++23 print the whole range with `std::print("{:n}", v)`, which separates elements with `, ` and adds no brackets.

### Question 4 [tricky] ([range.take.view], [iterators.common], [range.utility.conv.to])

Which of the marked lines fails to compile in C++23?

```cpp
#include <ranges>
#include <vector>

int main() {
  auto r = std::views::iota(0) | std::views::take(5);
  std::vector<int> a(r.begin(), r.end());                   // 1
  auto c = r | std::views::common;
  std::vector<int> b(c.begin(), c.end());                   // 2
  auto d = std::ranges::to<std::vector>(r);                 // 3
}
```

A. Line 1
B. Lines 1 and 3
C. Line 2
D. None of them

**Answer (A):** Line 1

**Why:** `views::iota(0)` is unbounded and not sized, so `take(5)` iterates with a `counted_iterator` and ends with a sentinel of a different type. The vector's iterator-pair constructor needs both arguments to have the same iterator type, so line 1 does not compile. `views::common` wraps both ends in `common_iterator`, which fixes line 2, and `ranges::to` accepts any range, so line 3 is fine too.

### Question 5 [tricky] ([reverse.iter.cons], [reverse.iter.elem])

What does this program print?

```cpp
#include <cstdio>
#include <iterator>
#include <vector>

int main() {
  std::vector<int> v{10, 20, 30, 40};
  std::reverse_iterator<std::vector<int>::iterator> r(v.begin() + 2);
  std::printf("%d\n", *r);
}
```

A. `30`
B. `20`
C. `40`
D. Undefined behavior

**Answer (B):** `20`

**Why:** Constructing a reverse iterator from `it` makes `it` its base, and a reverse iterator denotes the element before its base. `v.begin() + 2` points at 30, so the reverse iterator dereferences to 20. Expecting 30 is the classic off-by-one: the conversion keeps the position between elements, not the element.

### Question 6 [tricky] ([range.access.cbegin], [const.iterators], [iterator.range])

In C++23, which of the marked lines is ill-formed?

```cpp
#include <iterator>
#include <ranges>
#include <span>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3};
  std::span<int> sp(v);
  *std::cbegin(sp) = 10;          // 1
  *std::ranges::cbegin(sp) = 20;  // 2
}
```

A. Both lines
B. Neither line; a span of non-const `int` is always writable
C. Only line 2
D. Only line 1

**Answer (C):** Only line 2

**Why:** C++23 changed `std::ranges::cbegin` to wrap a mutable iterator in `basic_const_iterator`, whose dereference yields `const int&`, so line 2 is ill-formed. The non-member `std::cbegin` was left alone: it calls `begin` on the span as const, and a span's const `begin()` returns its ordinary mutable iterator, so line 1 compiles and writes to `v[0]`. In C++20 both lines compiled.

### Question 7 [standardese] ([istream.iterator.cons], [istream.iterator.ops])

What does this program print?

```cpp
#include <cstdio>
#include <iterator>
#include <sstream>

int main() {
  std::istringstream is("1 2 3");
  std::istream_iterator<int> it(is);
  int x = 0;
  is >> x;
  std::printf("%d %d\n", *it, x);
}
```

A. `1 1`
B. `2 1`
C. `1 2`
D. Unspecified: it depends on when the iterator first reads

**Answer (C):** `1 2`

**Why:** [istream.iterator.cons] specifies that the stream constructor stores the stream and then performs the increment, which extracts the first value. By the time `is >> x` runs, 1 has already been consumed and cached in the iterator, so `x` receives 2 and `*it` returns the cached 1. The timing is specified, not left to the implementation, which is why constructing an `istream_iterator` consumes input even if it is never dereferenced.

### Question 8 [standardese] ([range.counted], [iterators.counted], [default.sentinel])

What is the type of `c`?

```cpp
#include <list>
#include <ranges>

std::list<int> l{1, 2, 3, 4};
auto c = std::views::counted(l.begin(), 2);
```

A. `std::ranges::subrange<std::list<int>::iterator>`
B. `std::ranges::take_view<std::ranges::ref_view<std::list<int>>>`
C. `std::span<int>`
D. `std::ranges::subrange<std::counted_iterator<std::list<int>::iterator>, std::default_sentinel_t>`

**Answer (D):** `std::ranges::subrange<std::counted_iterator<std::list<int>::iterator>, std::default_sentinel_t>`

**Why:** [range.counted] makes `views::counted(it, n)` a `span` for contiguous iterators, `subrange(it, it + n)` for other random-access iterators, and otherwise a `subrange` of a `counted_iterator` and `default_sentinel`. A list iterator is only bidirectional, so the last form is used, which is still a sized range because the count is stored. The first option would require computing `it + 2` up front, which a list iterator cannot do in constant time.

---

# Track: Library utilities

Type-safe unions, callable wrappers and compile-time checked formatting.

# Vocabulary types and std::format

> Value-semantic sum types, type-erased callables with const and move-only correctness, and compile-time checked text formatting in modern C++.

- **Source:** C++ Atlas (https://cppatlas.com/topics/vocabulary-types-and-format)
- **Track:** Library utilities
- **Estimated reading time:** 11 minutes
- **ISO C++ clauses:** [optional] (https://eel.is/c++draft/optional), [variant] (https://eel.is/c++draft/variant), [any] (https://eel.is/c++draft/any), [func.wrap.move] (https://eel.is/c++draft/func.wrap.move), [format.fmt.string] (https://eel.is/c++draft/format.fmt.string)
- **cppreference links:** [std::optional](https://en.cppreference.com/w/cpp/utility/optional), [std::variant](https://en.cppreference.com/w/cpp/utility/variant), [std::visit](https://en.cppreference.com/w/cpp/utility/variant/visit2), [std::any](https://en.cppreference.com/w/cpp/utility/any), [std::move_only_function](https://en.cppreference.com/w/cpp/utility/functional/move_only_function), [std::format](https://en.cppreference.com/w/cpp/utility/format/format), [std::print](https://en.cppreference.com/w/cpp/io/print)
- **Prerequisites:** copy-and-move, optional-expected-and-error-codes

Modern standard C++ replaces sentinel integers (`-1`), `void*` user-data pointers, and stateful `std::ostream` manipulators with **vocabulary types**: value-semantic abstractions that encode presence, alternatives, callable ownership, and formatting rules directly in the type system.

> **Mental model.** `std::optional<T>` represents `T + 1` states, `std::variant<Ts...>` represents a closed sum `T1 + T2 + ...`, and `std::any` represents an open type-erased slot. All three store small objects inline without touching the heap when possible, preserving value semantics.

## Algebraic types: optional, variant, and any

`std::optional<T>` models an object that may or may not exist using aligned inline storage for `T` plus a `bool` engaged flag—zero heap allocation. Calling `.value()` throws `std::bad_optional_access` when empty, whereas `*opt` and `opt->` are unchecked (undefined behavior if empty). C++23 adds monadic operations—`.and_then()`, `.transform()`, and `.or_else()`—so pipelines avoid nested `if (opt)` pyramids:

```cpp
#include <optional>
#include <string_view>

std::optional<int> parse_port(std::string_view text) {
    if (text == "443") return 443;
    return std::nullopt;
}

int resolve_port(std::optional<std::string_view> env_value) {
    return env_value
        .and_then(parse_port)
        .transform([](int port) { return port + 1000; })
        .or_else([]() -> std::optional<int> { return 8080; })
        .value();
}
```

`std::variant<Ts...>` is a type-safe discriminated union sized to the maximum size and alignment of its alternatives plus a compact index tag. Unlike `std::optional`, a default-constructed `std::variant` initializes its **first** alternative `T0` (wrap `std::monostate` as `T0` when an empty state is desired or `T0` is not default-constructible).

While `std::variant` normally always holds one active alternative, it can enter a rare degenerate state where `v.valueless_by_exception()` is `true` (`v.index() == std::variant_npos`). That happens only if an exception is thrown *during* type-changing assignment or `emplace()` after destroying the old alternative and before completing construction of the new one.

`std::any` trades a closed alternative list for open type erasure: it stores any `CopyConstructible` type, typically using a Small Buffer Optimization (SBO) for small nothrow-movable objects and allocating on the heap for larger ones. Access via `std::any_cast<T>(&a)` returns `nullptr` on type mismatch, whereas `std::any_cast<T>(a)` throws `std::bad_any_cast`.

## Exhaustive visitation and the overloaded pattern

Reading a `std::variant` with `std::get_if<T>(&v)` works for one case, yet `std::visit` enforces **compile-time exhaustiveness** across every alternative. The standard idiom combines a variadic inheritance wrapper `overloaded` with `using Ts::operator()...`:

```cpp
#include <cstddef>
#include <string>
#include <variant>

template <class... Ts>
struct overloaded : Ts... {
    using Ts::operator()...;
};

std::size_t payload_score(const std::variant<int, std::string>& item) {
    return std::visit(overloaded{
        [](int n) -> std::size_t { return static_cast<std::size_t>(n); },
        [](const std::string& s) -> std::size_t { return s.size(); },
    }, item);
}
```

Since C++20, aggregate Class Template Argument Deduction deduces `overloaded` without an explicit deduction guide (add `template <class... Ts> overloaded(Ts...) -> overloaded<Ts...>;` only if targeting C++17). Note that `std::visit` checks `valueless_by_exception()` internally and throws `std::bad_variant_access` if any visited variant is valueless.

> **Pitfall.** Avoid writing a catch-all `[](const auto&) {}` arm inside `overloaded` unless deliberate fallback behavior is required: a generic lambda silently swallows newly added variant alternatives and defeats compile-time exhaustiveness checking.

## Callable wrappers: std::function vs. std::move_only_function

For over a decade, `std::function<R(Args...)>` was the default type-erased callback wrapper, yet it carries three structural flaws:

1. **Copy requirement:** `std::function` demands a `CopyConstructible` target, rejecting lambdas that capture `std::unique_ptr`, `std::jthread`, or move-only futures.
2. **Broken `const` propagation:** `std::function::operator()` is always `const`-qualified regardless of whether the wrapped callable mutates captured state. Calling a `const std::function` can mutate `[x = 0]() mutable { return ++x; }` silently.
3. **RTTI and throwing empty checks:** `std::function` stores RTTI for `.target_type()` and checks for null on every invocation to throw `std::bad_function_call`.

C++23 `std::move_only_function<Sig>` fixes all three. Its template signature encodes cv-qualifiers, ref-qualifiers (`&` / `&&`), and `noexcept` directly into the wrapper interface:

```cpp
#include <functional>
#include <memory>
#include <utility>

int run_task() {
    auto token = std::make_unique<int>(42);
    std::move_only_function<int() const noexcept> fn =
        [t = std::move(token)]() noexcept { return *t; };

    const auto& readonly_fn = fn;
    return readonly_fn();
}
```

Without `const` in `std::move_only_function<int()>`, calling through `const auto&` fails to compile; with `noexcept` in the signature, only `noexcept` callables bind and calling `fn()` is itself `noexcept`. Unlike `std::function`, invoking an empty `std::move_only_function` is undefined behavior rather than throwing, eliminating a conditional check and dropping RTTI overhead.

> **Standardese.** `[func.wrap.func]` permits `std::function::operator() const` to invoke non-`const` callable objects without propagating `const` correctness. `[func.wrap.move]` resolves this in C++23 by encoding the exact `const`, `&`/`&&`, and `noexcept` qualifiers in the template parameter of `std::move_only_function`.

## Compile-time checked std::format and std::print

C++20 `<format>` and C++23 `<print>` replace both type-unsafe `printf` varargs and verbose stateful `std::ostream` manipulators (`std::hex`, `std::setw` leaking across statements).

`std::format` achieves safety without runtime format parsing bugs by accepting `std::format_string<Args...>`, whose constructor is `consteval`:

```cpp
#include <format>
#include <print>
#include <string>
#include <vector>

struct Point {
    int x;
    int y;
};

template <>
struct std::formatter<Point> {
    constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
    auto format(const Point& p, std::format_context& ctx) const {
        return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
    }
};

void emit_report() {
    Point origin{3, 4};
    std::vector<int> samples{10, 20, 30};
    std::string text = std::format("pt={} samples={}", origin, samples);
    std::println("{}", text);
}
```

Because `format_string` runs at compile time, passing `"{:d}"` for a `std::string` or mismatched placeholder counts fails compilation immediately. When a format pattern genuinely comes from runtime configuration, opt in explicitly with `std::vformat(fmt, std::make_format_args(arg1, arg2))`—noting that after defect report P2905R2, `std::make_format_args` requires **lvalue** arguments so the returned `format_args` object cannot dangle on temporaries.

C++23 also adds range formatting directly (`std::format("{}", vec)`) and `<print>` (`std::print`, `std::println`), which write directly to `FILE*` or `stdout` without intermediate `std::string` heap allocations and support UTF-8 console output cleanly.

> **Pitfall.** Calling `std::format(runtime_string, x)` fails to compile because `std::format_string<Args...>` requires a compile-time constant string. Use `std::vformat(runtime_string, std::make_format_args(x))` with named lvalue variables when the format string is dynamic.

## Choosing the right utility abstraction

Matching each tool to its ownership and dispatch trade-offs prevents accidental heap allocations, broken `const` invariants, and unchecked runtime formatting errors.

| Type | Heap allocation | Copyable vs move-only | Failure or empty behavior | Best use case |
| --- | --- | --- | --- | --- |
| `std::optional<T>` | Never (inline) | Inherits from `T` | `.value()` throws; `*opt` is UB | Nullable values and optional fields |
| `std::variant<Ts...>` | Never (inline) | Inherits from `Ts...` | `std::get` throws; may go valueless on throw | Closed AST/state machine alternatives |
| `std::any` | SBO then heap | Requires `CopyConstructible` | `any_cast` throws or returns `nullptr` | Open heterogeneous property bags |
| `std::function<Sig>` | SBO then heap | Requires `CopyConstructible` | Empty call throws `bad_function_call` | Legacy copyable callbacks |
| `std::move_only_function<Sig>` | SBO then heap | Move-only (`const`/`noexcept` safe) | Empty call is UB | Modern single-owner tasks and handlers |

## What to remember

- Use `std::optional` monadic methods (`and_then`, `transform`, `or_else`) to chain nullable computations cleanly without heap allocation.
- Prefer `std::visit(overloaded{...}, v)` over `get_if` chains so the compiler enforces handling of every `std::variant` alternative.
- Switch callbacks from `std::function` to C++23 `std::move_only_function` to accept `std::unique_ptr` captures and preserve `const` and `noexcept` qualifiers.
- `std::format` and `std::print` validate format strings at compile time via `consteval` `std::format_string`; use `std::vformat` with lvalue arguments only when runtime format strings are unavoidable.

## Concept Map Outline

- **Vocabulary types and format:** Modern C++ encodes optionality, sum types, qualified callables, and checked formatting directly in types.
  - **std::optional values:** Stores T inline plus an engaged boolean with zero heap allocation.
    - **Checked vs unchecked access:** Calling value() throws bad_optional_access while operator* assumes engagement.
    - **C++23 monadic ops:** and_then, transform, and or_else chain optional steps cleanly.
      - **Flat error pipelines:** Monadic combinators forward nullopt cleanly without nested conditional branches.
  - **std::variant sum types:** Discriminated union sized to the largest alternative plus an active index.
    - **overloaded and std::visit:** Variadic lambda inheritance enforces exhaustive compile-time dispatch across alternatives.
      - **Avoid catch-all arms:** Skipping generic auto lambdas preserves compiler errors on new alternatives.
    - **valueless_by_exception:** Occurs only if type-changing assignment throws after destroying the old alternative.
  - **std::any open erasure:** Type-erased container storing any CopyConstructible value via SBO or heap.
    - **any_cast pointer vs value:** Pointer any_cast returns nullptr on mismatch while value cast throws bad_any_cast.
  - **Callable wrappers:** Type-erased invokables differ sharply in copyability and const propagation.
    - **std::function pitfalls:** Requires CopyConstructible targets and breaks const correctness on mutable lambdas.
    - **move_only_function:** C++23 wrapper supports unique_ptr captures and honors const and noexcept qualifiers.
      - **No empty-call overhead:** Calling an empty move_only_function is UB, removing branches and RTTI.
  - **std::format and std::print:** Type-safe formatting checked at compile time with zero stream state.
    - **consteval format_string:** Rejects mismatched placeholders at compile time; dynamic strings require std::vformat.
      - **Lvalues in make_format_args:** Defect report P2905R2 restricts make_format_args to lvalues to avoid dangling.
    - **Custom std::formatter:** Specialize parse and format to integrate user types and C++23 std::println.

## Standardese Quiz Questions

### Question 1 [warmup] ([variant.ctor], [variant.monostate])

Why does std::variant<NonDefault, int> fail to default-construct, and what standard helper fixes it?

```cpp
struct NonDefault { explicit NonDefault(int) {} };
std::variant<NonDefault, int> v;
```

A. std::variant default-constructs its first alternative (NonDefault); placing std::monostate first makes the variant default-constructible
B. std::variant requires every alternative to be default-constructible
C. std::variant always starts empty like std::optional
D. std::variant selects int automatically when the first alternative lacks a default constructor

**Answer (A):** std::variant default-constructs its first alternative (NonDefault); placing std::monostate first makes the variant default-constructible

**Why:** A default-constructed std::variant constructs its zero-indexed alternative. If the first type is not default-constructible, std::variant's default constructor is deleted; putting std::monostate as the first alternative provides a lightweight empty initial state.

### Question 2 [warmup] ([func.wrap.func.con], [func.wrap.move])

Why does storing a lambda that captures std::unique_ptr<int> fail with std::function<int()> but succeed with std::move_only_function<int()>?

```cpp
auto p = std::make_unique<int>(7);
std::move_only_function<int()> f = [p = std::move(p)] { return *p; };
```

A. std::function cannot store lambdas with captures at all
B. std::function requires stored callables to be CopyConstructible, whereas std::move_only_function requires only MoveConstructible
C. std::move_only_function stores pointers without calling destructors
D. std::function only works with function pointers

**Answer (B):** std::function requires stored callables to be CopyConstructible, whereas std::move_only_function requires only MoveConstructible

**Why:** std::function mandates CopyConstructible targets because std::function itself is copyable. C++23 std::move_only_function drops copyability, enabling move-only captures such as std::unique_ptr.

### Question 3 [tricky] ([func.wrap.func.inv], [func.wrap.move.inv])

What happens when calling f() through const std::function<int()>& vs const std::move_only_function<int()>& wrapping a mutable lambda?

```cpp
const std::function<int()> a = [n = 0]() mutable { return ++n; };
const std::move_only_function<int()> b = [n = 0]() mutable { return ++n; };
```

A. Both fail to compile because calling a mutable lambda through const is ill-formed
B. Both compile and increment n on every call
C. a compiles and mutates n despite being const; b fails to compile because std::move_only_function<int()> does not declare a const operator()
D. b compiles while a throws std::bad_function_call

**Answer (C):** a compiles and mutates n despite being const; b fails to compile because std::move_only_function<int()> does not declare a const operator()

**Why:** std::function::operator() is always const-qualified regardless of the wrapped callable, silently allowing mutation through a const std::function. std::move_only_function honors qualifiers in its signature: const invocations require std::move_only_function<int() const>.

### Question 4 [tricky] ([format.arg.store])

Why does std::vformat(fmt, std::make_format_args(42)) fail to compile under C++20/23 after DR P2905R2?

```cpp
std::string fmt = "{}";
auto s = std::vformat(fmt, std::make_format_args(42));
```

A. std::vformat does not accept integers
B. std::format_args only accepts std::string arguments
C. std::make_format_args returns void
D. std::make_format_args takes Args&... (lvalue references) to prevent storing dangling pointers to temporaries inside format_args

**Answer (D):** std::make_format_args takes Args&... (lvalue references) to prevent storing dangling pointers to temporaries inside format_args

**Why:** Defect report P2905R2 changed std::make_format_args from forwarding references (Args&&...) to lvalue references (Args&...) so callers cannot accidentally bind temporaries like 42 or std::string{} whose lifetime ends before std::vformat runs.

### Question 5 [standardese] ([variant.status], [variant.assign])

Under what circumstance can std::variant::valueless_by_exception() become true?

A. Whenever a variant holds std::monostate
B. When an exception is thrown during type-changing assignment or emplace() after the previous alternative was destroyed and before the new one finishes constructing
C. Whenever a variant is moved from
D. Whenever std::get<T> fails with std::bad_variant_access

**Answer (B):** When an exception is thrown during type-changing assignment or emplace() after the previous alternative was destroyed and before the new one finishes constructing

**Why:** According to [variant.status], a variant never becomes valueless during normal construction or moves; it becomes valueless_by_exception() only if an exception interrupts a type-changing assignment or emplace() between destroying the old value and constructing the replacement.

### Question 6 [standardese] ([func.wrap.move.inv], [func.wrap.func.inv])

What distinguishes invoking an empty std::move_only_function from invoking an empty std::function?

A. Calling an empty std::move_only_function is undefined behavior, whereas calling an empty std::function throws std::bad_function_call
B. Both throw std::bad_function_call
C. Calling an empty std::move_only_function returns a default-constructed R{}
D. std::move_only_function cannot be default-constructed or empty

**Answer (A):** Calling an empty std::move_only_function is undefined behavior, whereas calling an empty std::function throws std::bad_function_call

**Why:** Under [func.wrap.move.inv], invoking an empty std::move_only_function has a precondition that *this is non-empty (undefined behavior if violated), avoiding the branch and exception path mandated by std::function in [func.wrap.func.inv].

# optional, variant and any

> Three vocabulary types answer three different questions. optional is a value or nothing, variant is exactly one of a closed list, and any is one of an open set, checked at run time. Each has a precise rule for how it can be wrong, and those rules are the part worth knowing.

- **Source:** C++ Atlas (https://cppatlas.com/topics/optional-variant-any)
- **Track:** Library utilities
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [optional] (https://eel.is/c++draft/optional), [optional.observe] (https://eel.is/c++draft/optional.observe), [optional.comp.with.t] (https://eel.is/c++draft/optional.comp.with.t), [variant] (https://eel.is/c++draft/variant), [variant.ctor] (https://eel.is/c++draft/variant.ctor), [variant.assign] (https://eel.is/c++draft/variant.assign), [variant.mod] (https://eel.is/c++draft/variant.mod), [variant.visit] (https://eel.is/c++draft/variant.visit), [variant.get] (https://eel.is/c++draft/variant.get), [any] (https://eel.is/c++draft/any), [any.cons] (https://eel.is/c++draft/any.cons)
- **cppreference links:** [std::optional](https://en.cppreference.com/w/cpp/utility/optional), [std::variant](https://en.cppreference.com/w/cpp/utility/variant), [std::variant::valueless_by_exception](https://en.cppreference.com/w/cpp/utility/variant/valueless_by_exception), [std::visit](https://en.cppreference.com/w/cpp/utility/variant/visit), [std::any](https://en.cppreference.com/w/cpp/utility/any), [std::any_cast](https://en.cppreference.com/w/cpp/utility/any/any_cast)
- **Prerequisites:** copy-and-move, exceptions-and-stack-unwinding

## The one idea

These three types are all "a value that might be one of several things", and they differ in who knows the answer. With `optional<T>`, the type says the choices are a `T` or nothing. With `variant<A, B, C>`, the type lists every alternative, so the compiler can check that you handled all of them. With `any`, the type says nothing; only the object knows what it holds, and the check moves to run time.

All three store the value inside the object. None of them allocates for `optional` or `variant`; the standard forbids it. `any` is allowed to allocate and usually does for large types.

> **Mental model.** `optional` adds one state to a type, `variant` makes a tagged union you cannot misread, and `any` is a type-erased box that remembers only what it was constructed from.

The monadic operations of `optional` (`and_then`, `transform`, `or_else`) and `std::expected` belong to the topic on `optional-expected-and-error-codes`; this one is about the state model of each type.

## optional: engaged or empty

An `optional<T>` is either engaged, holding a `T`, or empty. The two ways to read it differ in what happens when you are wrong.

```cpp
#include <optional>
#include <cstdio>

int main() {
  std::optional<int> o;
  try {
    (void)o.value();             // throws std::bad_optional_access
  } catch (const std::bad_optional_access&) {
    std::puts("empty");
  }
  // *o;                         // undefined behavior: precondition is has_value()
  std::printf("%d\n", o.value_or(7));  // 7
}
```

`operator*` and `operator->` have the precondition that the optional is engaged, and violating it is undefined behavior. `value()` checks and throws `bad_optional_access`. Use `*` after a test, and `value()` or `value_or` when you do not want to prove it.

### Assignment follows the engaged states

Assigning to an optional does whatever the pair of states calls for. If both sides are engaged, the contained value is assigned. If the target is empty and the source is engaged, a value is constructed. If the target is engaged and the source is empty, the value is destroyed. If both are empty, nothing happens. Assigning a plain `T` works like the first two cases. `emplace` is different: it always destroys the old value first and then constructs the new one, so it needs no assignment operator.

```cpp
#include <optional>
#include <cstdio>

struct Noisy {
  Noisy() = default;
  Noisy(int) { std::puts("construct"); }
  Noisy& operator=(int) { std::puts("assign"); return *this; }
};

int main() {
  std::optional<Noisy> o;
  o = 1;   // construct: the optional was empty
  o = 2;   // assign: the optional was engaged
  o = {};  // destroys the value; o is empty again
}
```

### The `optional<bool>` trap

`optional` converts to `bool` to ask whether it is engaged, not what it holds. For `optional<bool>`, the two questions look identical and are not.

```cpp
#include <optional>
#include <cstdio>

int main() {
  std::optional<bool> flag = false;
  if (flag) std::puts("engaged");   // prints: the test is has_value()
  if (*flag) std::puts("true");     // does not print
}
```

The conversion is `explicit`, so `bool b = flag;` does not compile, but contexts such as `if`, `!` and `&&` still apply it. When the payload is a boolean, say `flag.has_value()` or `flag.value_or(false)` so the reader can tell which you meant.

### Comparisons

Comparing two optionals treats an empty one as smaller than any engaged one, and two empty ones as equal. Comparing an optional with a plain `T` compares the value if engaged, and an empty optional is less than every `T`.

```cpp
#include <optional>
#include <cstdio>

int main() {
  std::optional<int> n;                           // empty
  std::printf("%d %d %d\n", n < 0, n == 0, n < -1);  // 1 0 1
  std::printf("%d\n", n == std::nullopt);            // 1
}
```

Ordering is therefore total, which makes optionals usable as keys, but it can surprise: an empty optional is below `INT_MIN`.

## variant: a union that knows what it holds

A `variant<A, B, C>` holds exactly one alternative, and `index()` says which. A default-constructed variant holds a value-initialized first alternative, so if the first type has no default constructor, the variant does not either. The standard remedy is `std::monostate`, an empty type with all comparisons equal, placed first.

```cpp
#include <variant>
#include <string>
#include <cstdio>

struct NoDefault { NoDefault(int) {} };

int main() {
  std::variant<std::string, int> a;            // holds "" at index 0
  std::variant<std::monostate, NoDefault> b;   // OK because of monostate
  std::printf("%zu %zu\n", a.index(), b.index());  // 0 0
}
```

Duplicate alternatives are legal, but then the type-based accessors are ambiguous. You reach them with `in_place_index<N>` and `get<N>`.

### get, get_if and visit

`get<T>(v)` or `get<N>(v)` returns a reference and throws `bad_variant_access` if the variant holds something else. `get_if<T>(&v)` takes a pointer and returns a pointer, null on mismatch, so it fits in an `if` and cannot throw. `holds_alternative<T>(v)` only asks the question.

`std::visit` is the way to handle every alternative. It calls a callable with the held value, and the compiler requires that the callable accepts all of them.

```cpp
#include <variant>
#include <string>
#include <cstdio>

template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; };

int main() {
  std::variant<int, std::string> v = std::string("hi");
  std::visit(overloaded{
    [](int i)                { std::printf("int %d\n", i); },
    [](const std::string& s) { std::printf("string %s\n", s.c_str()); },
  }, v);                                        // string hi
}
```

The `overloaded` idiom inherits every lambda's call operator, so overload resolution picks the arm. Since C++20 the deduction guide it needed in C++17 is generated automatically for aggregates. Adding a new alternative makes any visitor that does not cover it fail to compile, which is the reason to prefer `visit` over a chain of `holds_alternative` tests. All arms must return the same type unless you name one with `visit<R>` (C++20).

### The converting constructor

Initializing a variant from a value picks the alternative by overload resolution over an imaginary function `F(T_i)` for each alternative. Originally this admitted far too much: `variant<bool, string>` built from a string literal picked `bool`, because pointer-to-bool is a standard conversion and beat the user-defined conversion to `string`.

The fix, P0608R3 plus P1957R2 for the pointer case, was adopted for C++20 and is applied by current library implementations to older modes as well. Alternatives that would need a narrowing conversion are not candidates, and pointer-to-bool counts as narrowing.

```cpp
#include <variant>
#include <string>
#include <cstdio>

int main() {
  std::variant<bool, std::string> v = "hello";
  std::printf("%zu\n", v.index());   // 1: string; bool is not a candidate
  // std::variant<int, double> w = 1L;  // ill-formed: both conversions narrow
}
```

If two alternatives accept the argument equally well, there is no unique choice and the constructor is not available. `variant<int, int> v = 5;` is ill-formed for that reason; write `variant<int, int> v{std::in_place_index<0>, 5};`.

### valueless_by_exception

A variant has to hold something, but changing alternative is a destroy followed by a construct, and the construct can throw. With no allocation allowed, the old value cannot be kept, so the variant may end up in a state where it holds nothing. That is `valueless_by_exception()`. Then `index()` returns `variant_npos`, `get` throws `bad_variant_access`, and `visit` throws `bad_variant_access`.

```cpp
#include <variant>
#include <string>
#include <cstdio>

struct Bad {
  Bad(int) {}
  Bad(const Bad&) { throw 1; }
};

int main() {
  std::variant<std::string, Bad> v = "text";
  try { v = Bad{1}; } catch (int) {}
  std::printf("%d\n", v.valueless_by_exception());  // 1 with libstdc++
}
```

> **Standardese.** [variant.mod] and [variant.assign] say that if an exception is thrown while initializing the new alternative during `emplace` or a type-changing assignment, the variant might not hold a value. Move assignment between different alternatives, where the move constructor throws, is the case cppreference lists as always producing the valueless state. Implementations may avoid it by building a temporary first when the alternative's move is `noexcept`, so what the example prints is implementation behavior, not a promise.

The practical rule: keep alternatives nothrow-movable and valueless is nearly unreachable, and `std::visit` throwing on it is then a bug check rather than a case to handle.

## any: type erasure with a run-time check

`std::any` holds a copy of any copy-constructible value. It stores the decayed type, so `any a = "hello"` holds a `const char*`, not a `std::string`. The standard encourages implementations to keep small objects inside the `any` and avoid allocating, but does not require it, and what counts as small differs by library.

Copyability is a hard requirement because an `any` can itself be copied, and the copy must work for whatever it holds. That rules out `unique_ptr` and other move-only types, even if you never copy the `any`.

```cpp
#include <any>
#include <memory>
#include <string>
#include <cstdio>

int main() {
  std::any a = std::string("s");
  // std::any b = std::make_unique<int>(1);    // ill-formed: not copy-constructible
  std::printf("%d\n", std::any_cast<std::string>(&a) != nullptr);  // 1
  std::printf("%d\n", std::any_cast<int>(&a) != nullptr);          // 0
}
```

### any_cast has three shapes

`any_cast<T>(any&)` and `any_cast<T>(const any&)` return a value, and `any_cast<T&>` returns a reference. All of them throw `bad_any_cast` on a mismatch. The overload taking a pointer, `any_cast<T>(&a)`, returns a pointer and gives null on mismatch.

The match is exact, by dynamic type. There are no conversions, so an `any` holding an `int` does not yield a `long`, and one built from a literal does not yield a `std::string`.

```cpp
#include <any>
#include <string>
#include <cstdio>

int main() {
  std::any a = "hello";                  // holds const char*
  try {
    (void)std::any_cast<std::string>(a);
  } catch (const std::bad_any_cast&) {
    std::puts("bad_any_cast");           // printed
  }
  std::string s = std::any_cast<const char*>(a);  // OK: a const char* converts here
  std::printf("%s\n", s.c_str());
}
```

Use `any` when the set of types really is open, for example at a plugin boundary. If you can list the types, a `variant` is checked at compile time, cheaper, and cannot hold surprises.

## Choosing between them

| Need | Use |
| --- | --- |
| A value that may be absent | `optional<T>` |
| One of a known, closed set of types | `variant<...>` |
| An open set of types, checked at run time | `any` |
| Absent or an error value | `expected` (see the sibling topic) |

> **Pitfall.** `if (opt)` on an `optional<bool>`, and `get<T>(v)` on a variant that holds a different type, both compile and both do the wrong thing in a way tests with `true` data will not catch. Use `has_value()`, `get_if` and `visit`, which say what you mean.

## What to remember

- `optional`: `*o` on an empty optional is undefined behavior, `value()` throws `bad_optional_access`, and `value_or` supplies a fallback.
- Assigning an optional constructs, assigns or destroys according to which side is engaged; `emplace` destroys then constructs.
- `if (optional<bool>)` tests engagement, not the boolean. An empty optional compares less than every value and equal to `nullopt`.
- A default-constructed `variant` holds its first alternative, so use `monostate` first when that type has no default constructor.
- `get` throws on the wrong alternative, `get_if` returns null, and `visit` with an `overloaded` set checks at compile time that every alternative is handled.
- The converting constructor ignores narrowing candidates since the C++20 fix, so `variant<bool, string>` from a literal holds the string; ambiguous cases are ill-formed.
- A variant can become valueless after an exception during a type change; `index()` is then `variant_npos` and `visit` throws.
- `any` stores the decayed type and requires it to be copy constructible; `any_cast` matches the exact type, and the pointer form returns null instead of throwing.

## Concept Map Outline

- **optional, variant, any:** Three vocabulary types for a value that may be absent, one of a closed set, or anything.
  - **optional:** A T or nothing, stored inline with no allocation.
    - **Accessors:** operator* on an empty optional is undefined behavior; value() throws bad_optional_access.
    - **Assignment:** Constructs, assigns or destroys depending on which side is engaged; emplace destroys then constructs.
    - **optional<bool> trap:** if (opt) tests engagement, not the contained boolean.
    - **Comparisons:** An empty optional equals nullopt and is less than every value.
  - **variant basics:** Exactly one of a fixed list of alternatives, with index() saying which.
    - **Default construction:** Holds a value-initialized first alternative; put monostate first if that type has no default constructor.
    - **get versus get_if:** get throws bad_variant_access on mismatch; get_if takes a pointer and returns null.
    - **visit and overloaded:** visit with an overloaded lambda set forces every alternative to be handled at compile time.
  - **variant conversions:** How a value picks an alternative, and what happens when that goes wrong.
    - **Converting constructor:** Overload resolution over the alternatives; ties make the constructor unavailable.
    - **Narrowing excluded:** Since the C++20 fix, narrowing candidates are dropped, so a literal no longer picks bool.
    - **valueless_by_exception:** A throw during a type change can leave no value; index() is then variant_npos.
  - **any:** A type-erased box holding a copy of any copy-constructible value.
    - **Decayed storage:** any a = "hi" holds a const char*, not a std::string.
    - **Copy requirement:** The decayed type must be copy constructible, so move-only types are rejected.
    - **Small buffer:** Implementations are encouraged but not required to avoid allocating for small types.
    - **any_cast forms:** Value and reference forms throw bad_any_cast; the pointer form returns null.
  - **Choosing:** Pick by how much the type system knows about the alternatives.
    - **Closed set:** Use variant when you can list the types; it is checked at compile time.
    - **Open set:** Use any only when the types are genuinely unknown, and expect a run-time check.

## Standardese Quiz Questions

### Question 1 [warmup] ([optional.observe])

What does this program print?

```cpp
#include <optional>
#include <cstdio>

int main() {
  std::optional<bool> flag = false;
  if (flag) std::puts("A");
  if (flag.value()) std::puts("B");
}
```

A. Nothing
B. `A`
C. `B`
D. `A` then `B`

**Answer (B):** `A`

**Why:** The contextual conversion of an `optional` to `bool` reports whether it is engaged, and `flag` holds a value, so `A` is printed. `value()` returns the contained `false`, so `B` is not printed. The tempting answer is nothing, from reading `if (flag)` as testing the boolean inside.

### Question 2 [warmup] ([optional.observe])

Which statement about an empty `std::optional<int> o;` is correct?

A. `o.value()` throws `std::bad_optional_access`, while `*o` is undefined behavior
B. Both `o.value()` and `*o` throw `std::bad_optional_access`
C. `*o` returns a value-initialized `int`, and `o.value()` throws
D. Both `o.value()` and `*o` are undefined behavior

**Answer (A):** `o.value()` throws `std::bad_optional_access`, while `*o` is undefined behavior

**Why:** `operator*` has the precondition that the optional contains a value, so calling it on an empty optional is undefined behavior. `value()` is the checked accessor and throws `bad_optional_access`. Neither returns a default value; `value_or` is the accessor for that.

### Question 3 [warmup] ([variant.ctor])

What does this program print?

```cpp
#include <variant>
#include <string>
#include <cstdio>

int main() {
  std::variant<std::string, int> v;
  std::printf("%zu %zu\n", v.index(), std::get<0>(v).size());
}
```

A. `0 0`
B. `1 0`
C. It throws `std::bad_variant_access`
D. Undefined behavior: the variant is uninitialized

**Answer (A):** `0 0`

**Why:** A default-constructed variant holds a value-initialized first alternative, here an empty `std::string`, so the index is 0 and the size is 0. It is never empty and never holds an indeterminate `int` instead. If the first alternative were not default constructible, the variant would not be either.

### Question 4 [tricky] ([optional.comp.with.t])

What does this program print?

```cpp
#include <optional>
#include <cstdio>

int main() {
  std::optional<int> n;
  std::printf("%d%d%d\n", n < -1, n == 0, n > 0);
}
```

A. `000`, because comparing an empty optional is always false
B. `100`
C. `110`
D. Undefined behavior: `n` is empty

**Answer (B):** `100`

**Why:** An empty optional compares less than any value of `T`, so `n < -1` is true. `n == 0` is false because there is no value to equal 0, and `n > 0` is false because an empty optional is never greater than a value. The comparison operators do not dereference, so there is no undefined behavior.

### Question 5 [tricky] ([variant.ctor])

In C++20 mode, with a library that implements the P0608R3 and P1957R2 changes to the converting constructor, what does this print?

```cpp
#include <variant>
#include <string>
#include <cstdio>

int main() {
  std::variant<bool, std::string> v = "hello";
  std::printf("%zu\n", v.index());
}
```

A. `0`, because the array-to-pointer-to-bool conversion is a standard conversion
B. Ill-formed: the call is ambiguous
C. `1`
D. It throws `std::bad_variant_access`

**Answer (C):** `1`

**Why:** The converting constructor ignores alternatives that would need a narrowing conversion, and a pointer-to-bool conversion counts as narrowing. That leaves only `std::string`, so the index is 1. Before those changes `bool` won, because a standard conversion beats a user-defined one, which is the tempting answer.

### Question 6 [tricky] ([any.cons], [any.nonmembers])

What does this program print?

```cpp
#include <any>
#include <string>
#include <cstdio>

int main() {
  std::any a = "hello";
  try {
    std::string s = std::any_cast<std::string>(a);
    std::puts(s.c_str());
  } catch (const std::bad_any_cast&) {
    std::puts("bad");
  }
}
```

A. `hello`
B. `bad`
C. Ill-formed: `any` cannot hold a string literal
D. Undefined behavior: the cast reinterprets a `const char*`

**Answer (B):** `bad`

**Why:** An `any` stores the decayed type of its initializer, so `a` holds a `const char*`, not a `std::string`. `any_cast` requires an exact type match and performs no conversion, so it throws `bad_any_cast`. The cast `any_cast<const char*>(a)` would succeed.

### Question 7 [standardese] ([variant.ctor])

Is this program well-formed in C++23?

```cpp
#include <variant>

int main() {
  std::variant<int, int> v = 5;
  (void)v;
}
```

A. Yes; it holds alternative 0
B. Yes; it holds alternative 1, the last match
C. No: the converting constructor is not viable because no single alternative is selected
D. Yes, but the behavior is undefined when the variant is read

**Answer (C):** No: the converting constructor is not viable because no single alternative is selected

**Why:** The converting constructor selects an alternative by overload resolution over `F(int)` twice, which is ambiguous, so the constructor does not participate and the initialization is ill-formed. There is no tie-break by position. To pick an alternative explicitly use `std::in_place_index<0>`.

### Question 8 [standardese] ([any.cons])

Is this program well-formed in C++23?

```cpp
#include <any>
#include <memory>

int main() {
  std::any a = std::make_unique<int>(1);
  (void)a;
}
```

A. Yes; the `any` is simply not copyable
B. Yes; it holds a copy of the pointee
C. No: the decayed type must be copy constructible
D. Yes, but copying `a` later throws `bad_any_cast`

**Answer (C):** No: the decayed type must be copy constructible

**Why:** The converting constructor of `any` only participates when the decayed type is copy constructible, because the `any` itself must be copyable for whatever it holds. `unique_ptr<int>` is not, so no constructor is viable and the program is ill-formed. A move-only payload is rejected even if you never copy the `any`.

# pair, tuple and the tuple protocol

> A tuple is a struct whose members have numbers instead of names. The interesting parts are how it is built, how tuples of references work as a multiple-assignment device, and how the tuple protocol lets any type take part in structured bindings and in tuple algorithms.

- **Source:** C++ Atlas (https://cppatlas.com/topics/tuple-and-pair)
- **Track:** Library utilities
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [pairs] (https://eel.is/c++draft/pairs), [tuple] (https://eel.is/c++draft/tuple), [tuple.cnstr] (https://eel.is/c++draft/tuple.cnstr), [tuple.assign] (https://eel.is/c++draft/tuple.assign), [tuple.creation] (https://eel.is/c++draft/tuple.creation), [tuple.rel] (https://eel.is/c++draft/tuple.rel), [tuple.apply] (https://eel.is/c++draft/tuple.apply), [tuple.helper] (https://eel.is/c++draft/tuple.helper), [dcl.struct.bind] (https://eel.is/c++draft/dcl.struct.bind)
- **cppreference links:** [std::pair](https://en.cppreference.com/w/cpp/utility/pair), [std::tuple](https://en.cppreference.com/w/cpp/utility/tuple), [std::tie](https://en.cppreference.com/w/cpp/utility/tuple/tie), [std::forward_as_tuple](https://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple), [std::apply](https://en.cppreference.com/w/cpp/utility/apply), [std::make_from_tuple](https://en.cppreference.com/w/cpp/utility/make_from_tuple), [std::ignore](https://en.cppreference.com/w/cpp/utility/tuple/ignore), [tuple-like and pair-like](https://en.cppreference.com/w/cpp/utility/tuple/tuple-like)
- **Prerequisites:** structured-bindings, forwarding-references-and-perfect-forwarding, three-way-comparison

## The one idea

`std::pair<A, B>` and `std::tuple<A, B, C...>` are structs with anonymous members. They give you construction, copying, swapping and lexicographic comparison for free, in exchange for losing every name. That trade is good for glue code, such as returning two values or forwarding an argument pack, and bad for anything that lives longer than a statement.

Two ideas make the family more than a convenience. First, a tuple can hold references, which turns it into a bundle of lvalues you can assign through. Second, the *tuple protocol*, a trio of `tuple_size`, `tuple_element` and `get`, is not tied to `std::tuple`, and any type can implement it.

> **Mental model.** A tuple is a struct without member names. A tuple of references is a struct of aliases. The protocol is the interface that lets generic code, and structured bindings, treat any struct that way.

## Construction

Both types have the constructors you expect: default, copy and move, and element-wise. The element-wise constructors are *conditionally explicit*: the constructor is `explicit` only if some element conversion is explicit. This is why initialization from braces works for ordinary types and fails for the explicit ones.

```cpp
#include <tuple>
#include <string>

struct Explicit { explicit Explicit(int) {} };

int main() {
  std::tuple<std::string, int> a = {"x", 1};   // OK: every conversion is implicit
  std::tuple<std::string> b = "x";             // OK: const char* converts implicitly
  std::tuple<Explicit> c{1};                   // OK: direct initialization
  // std::tuple<Explicit> d = {1};             // ill-formed: would use an explicit constructor
  (void)a; (void)b; (void)c;
}
```

Class template argument deduction works too, so `std::tuple t{1, 2.5, 'c'}` deduces `tuple<int, double, char>`. One trap: a single tuple argument is copied rather than nested, so `std::tuple t{some_tuple}` has the type of `some_tuple`.

### Piecewise construction

Sometimes the elements cannot be moved or copied at all, and you need to build each one in place from its own argument list. `pair` has a constructor tagged with `std::piecewise_construct` that takes one tuple of arguments per member. It exists for `emplace` on maps, which must build a `pair<const K, V>` from loose arguments, and it is where `forward_as_tuple` earns its keep.

```cpp
#include <map>
#include <tuple>
#include <utility>

struct Pinned {
  Pinned(int, int) {}
  Pinned(const Pinned&) = delete;
};

int main() {
  std::map<int, Pinned> m;
  // m.emplace(1, 2, 3);   // ill-formed: pair has no three-argument constructor
  m.emplace(std::piecewise_construct,
            std::forward_as_tuple(1),         // key built from (1)
            std::forward_as_tuple(2, 3));     // value built from (2, 3)
}
```

`std::map::try_emplace` covers the common case without the tuples, and is the better tool when it applies.

## Tuples of references

`std::tie(a, b)` returns a `tuple<A&, B&>`. Assigning a tuple or pair to it assigns each referenced variable, which is the closest C++ gets to multiple assignment. It is also the idiom for unpacking when you do not want new variables.

```cpp
#include <tuple>
#include <utility>
#include <cstdio>

int main() {
  int a = 1, b = 2;
  std::tie(a, b) = std::make_pair(b, a);   // a == 2, b == 1: the pair holds copies
  std::printf("%d %d\n", a, b);

  double d;
  std::tie(std::ignore, d) = std::make_pair(1, 2.5);  // ignore swallows the first value
  std::printf("%g\n", d);
}
```

`std::ignore` is an object whose assignment operator accepts anything and does nothing. Do not write `std::tie(a, b) = std::tie(b, a)` as a swap: both sides alias the same variables, and the second element reads an already overwritten value.

Three factories produce tuples of different shapes, and the differences matter.

| Call | Result for `int x; make(x, 1)` | Why |
| --- | --- | --- |
| `make_tuple(x, 1)` | `tuple<int, int>` | decays and copies every argument |
| `tie(x)` | `tuple<int&>` | references to lvalues only |
| `forward_as_tuple(x, 1)` | `tuple<int&, int&&>` | forwarding references, nothing is copied |

`make_tuple` also unwraps `std::reference_wrapper`, so `make_tuple(std::ref(a), std::cref(b))` is a `tuple<int&, const int&>`, and it decays arrays and functions, so `make_tuple("hi")` is a `tuple<const char*>`.

> **Pitfall.** `forward_as_tuple` is made for passing arguments straight on, within one full expression. Storing its result is dangerous: `auto t = std::forward_as_tuple(std::string("x"));` holds an `std::string&&` to a temporary that dies at the semicolon, and reading it afterwards is undefined behavior.

### Assignment goes through the references

References cannot be rebound, so assigning a `pair<int&, int>` to another assigns the *referred-to* object. The same holds for `tuple`.

```cpp
#include <utility>
#include <cstdio>

int main() {
  int a = 1, b = 2;
  std::pair<int&, int> p{a, 0}, q{b, 0};
  p = q;                          // a = b; p still refers to a
  std::printf("%d %d\n", a, b);   // 2 2
}
```

C++23 adds assignment operators that are `const`-qualified, for tuples and pairs whose elements are assignable through a const reference. A `const tuple<int&>` can therefore be assigned to. The reason is range proxies: `views::zip` yields prvalue tuples of references, and and the `indirectly_writable` concept requires that a const-qualified proxy returned by dereferencing an iterator can be assigned to. That is the reason for the change, and it is where you meet it in practice. Zipping itself belongs to the ranges topics.

## Comparison

Pairs and tuples compare lexicographically: the first position that differs decides, and equal prefixes defer to the rest. Tuples of different sizes cannot be compared. Since C++20, `<=>` is provided, and its category is the weakest category among the elements, so `tuple<int, double>` gives `std::partial_ordering` because `double` can be unordered, while `tuple<int, int>` gives `std::strong_ordering`. The relational operators `<`, `>`, `<=` and `>=` are rewritten in terms of it, and the separate per-operator overloads of earlier standards were removed.

The elements may differ in type as long as each pair of corresponding elements is comparable, so `tuple<int, std::string>` and `tuple<long, std::string>` compare.

This is why `std::tie(a.x, a.y) < std::tie(b.x, b.y)` is the classic way to write a multi-key `operator<` before C++20. With C++20, a defaulted `operator<=>` on a named struct does it better. See the three-way comparison topic.

## apply, make_from_tuple and tuple_cat

`std::apply(f, t)` calls `f` with the elements of `t` as arguments, and works for any tuple-like type. `std::make_from_tuple<T>(t)` constructs a `T` the same way. `std::tuple_cat` concatenates tuples, pairs and arrays into one tuple; the result type holds the elements in order.

```cpp
#include <tuple>
#include <utility>
#include <string>
#include <cstdio>

struct User {
  User(int id, std::string name) : id(id), name(std::move(name)) {}
  int id; std::string name;
};

int main() {
  auto sum = std::apply([](int a, int b) { return a + b; }, std::make_pair(3, 4));
  auto u = std::make_from_tuple<User>(std::tuple<int, const char*>{1, "ann"});
  auto all = std::tuple_cat(std::tuple<int>{1}, std::pair<int, int>{2, 3});
  static_assert(std::tuple_size_v<decltype(all)> == 3);
  std::printf("%d %s\n", sum, u.name.c_str());   // 7 ann
}
```

Together with a pack expansion, `apply` is how a stored argument pack is called later, which is the technique behind deferred-call machinery.

## The tuple protocol

Three things make a type tuple-like to the library and to structured bindings: a specialization of `std::tuple_size<T>`, a specialization of `std::tuple_element<I, T>`, and a `get<I>` found either as a member or by argument-dependent lookup. A structured binding uses the protocol whenever `tuple_size<E>` is a complete type, ahead of its rule for plain structs.

```cpp
#include <tuple>
#include <string>
#include <cstdio>

struct Employee {
  std::string name;
  int id;
  template <std::size_t I> auto& get() & {
    if constexpr (I == 0) return name; else return id;
  }
};

template <> struct std::tuple_size<Employee> : std::integral_constant<std::size_t, 2> {};
template <std::size_t I> struct std::tuple_element<I, Employee> {
  using type = std::remove_reference_t<decltype(std::declval<Employee&>().get<I>())>;
};

int main() {
  Employee e{"ann", 7};
  auto& [n, i] = e;
  std::printf("%s %d\n", n.c_str(), i);   // ann 7
}
```

You write this only when a plain struct's own members are not what you want to expose. For a simple aggregate, structured bindings already work without any of it.

### tuple-like in C++23

C++23 formalized the idea with an exposition-only concept, *tuple-like*. The standard types that satisfy it are `array`, `pair`, `tuple` and `ranges::subrange`, with `std::complex` added in C++26. Several operations then accept any of them: `tuple` and `pair` can be constructed and assigned from other tuple-likes, so a `tuple<int, int>` can be built from an `array<int, 2>` or a `pair<int, int>`, and `apply`, `tuple_cat` and `make_from_tuple` work on all of them. Library support arrived unevenly; libstdc++ in GCC 16 accepts these, but verify against your own standard library before relying on interconversion between `tuple` and `array`.

## Layout, and when to use a struct

The standard gives no layout guarantees for `tuple`. Members need not appear in order in memory, and implementations are free to use empty-base tricks to squeeze out empty members. Do not reinterpret a tuple as an array or as a struct.

The practical rule for choosing between a tuple and a struct is lifetime and meaning. Use a tuple or pair for a local, short-lived grouping such as a function returning two values, a key for a sorted container, or a stored argument pack. As soon as the fields cross an interface, give them names. `result.first` and `result.second` say nothing, an `std::pair<int, int>` for a point and one for an interval are interchangeable by accident, and adding a third field to a struct does not break every `get<1>` in your codebase. A named aggregate with `= default` comparison costs nothing at run time and decomposes with structured bindings anyway.

## What to remember

- Pair and tuple are structs with numbered members; their element-wise constructors are `explicit` only if some element conversion is.
- `piecewise_construct` plus `forward_as_tuple` builds each element in place, which is what `map::emplace` needs for non-movable mapped types.
- `make_tuple` copies and decays, `tie` makes lvalue references, `forward_as_tuple` makes forwarding references that dangle if you store them.
- Assigning tuples of references assigns the referents; C++23 adds `const` assignment so proxy tuples work.
- Comparison is lexicographic and `<=>` yields the weakest category of the elements, so a `double` element gives `partial_ordering`.
- `apply`, `make_from_tuple` and `tuple_cat` operate on any tuple-like type.
- The protocol is `tuple_size`, `tuple_element` and `get`; structured bindings use it before the struct rule.
- There is no layout guarantee. Name your fields once the data leaves the statement it was created in.

## Concept Map Outline

- **pair, tuple, tuple protocol:** Structs with numbered members, plus the protocol that lets any type behave like one.
  - **Construction:** Element-wise, converting and piecewise ways to build pairs and tuples.
    - **Conditional explicit:** The element-wise constructor is explicit only when some element conversion is explicit.
    - **Deduction:** tuple t{1, 2.5} deduces element types, and a single tuple argument is copied, not nested.
    - **Piecewise:** piecewise_construct with forward_as_tuple builds each member in place, as map::emplace needs.
  - **Tuples of references:** A bundle of aliases that supports multiple assignment.
    - **make_tuple:** Decays and copies arguments, and unwraps reference_wrapper into references.
    - **tie:** Makes a tuple of lvalue references, so assigning to it assigns the variables.
    - **forward_as_tuple:** Forwarding references with no copies; storing the result can dangle.
    - **Assignment through:** Assigning tuples of references assigns the referents; C++23 adds const assignment for proxies.
    - **std::ignore:** Accepts any assignment and discards it, to skip a position in tie.
  - **Comparison:** Lexicographic ordering with a derived comparison category.
    - **Lexicographic:** The first differing element decides; sizes must match.
    - **Spaceship category:** The result is the weakest category of the elements, so a double gives partial_ordering.
  - **Tuple algorithms:** Functions that consume or combine tuple-like values.
    - **apply:** Calls a function with the elements of a tuple-like object as arguments.
    - **make_from_tuple:** Constructs a T from the elements of a tuple-like object.
    - **tuple_cat:** Flattens one level, concatenating tuples, pairs and arrays into one tuple.
  - **Tuple protocol:** tuple_size, tuple_element and get make any type tuple-like.
    - **Structured bindings:** Bindings use the protocol whenever tuple_size is complete, before the struct rule.
    - **tuple-like in C++23:** array, pair, tuple and subrange qualify, and tuple and pair convert from any of them.
  - **Practice:** Where tuples help and where a named struct is better.
    - **No layout guarantee:** Member order and padding are unspecified, so never reinterpret a tuple.
    - **Prefer a struct:** Once fields cross an interface, names beat first and second.

## Standardese Quiz Questions

### Question 1 [warmup] ([tuple.creation])

What does this program print?

```cpp
#include <tuple>
#include <cstdio>

int main() {
  int x = 1;
  auto a = std::make_tuple(x);
  auto b = std::tie(x);
  std::get<0>(a) = 2;
  std::printf("%d ", x);
  std::get<0>(b) = 3;
  std::printf("%d\n", x);
}
```

A. `1 3`
B. `2 3`
C. `1 1`
D. `2 2`

**Answer (A):** `1 3`

**Why:** `make_tuple` decays and copies its argument, so `a` owns its own `int` and writing to it leaves `x` at 1. `tie` builds a `tuple<int&>`, so writing through `b` changes `x`, giving 3.

### Question 2 [warmup] ([tuple.rel])

What does this program print?

```cpp
#include <tuple>
#include <string>
#include <cstdio>

int main() {
  using T = std::tuple<int, std::string, int>;
  T a{1, "b", 9};
  T b{1, "c", 0};
  std::printf("%d %d\n", a < b, a == b);
}
```

A. `0 0`
B. `1 1`
C. `0 1`
D. `1 0`

**Answer (D):** `1 0`

**Why:** Tuples compare lexicographically. The first elements are equal, the second elements decide because `"b" < "c"`, and the trailing `9 > 0` is never consulted. So `a < b` is 1 and `a == b` is 0.

### Question 3 [warmup] ([tuple.creation])

What is the value of `std::tuple_size_v<R>` for `R` as defined here?

```cpp
#include <tuple>
#include <utility>

using R = decltype(std::tuple_cat(std::tuple<int>{}, std::pair<int, int>{}, std::tuple<>{}));

int main() {}
```

A. 2, because the pair counts as one element
B. 3
C. It is ill-formed: `tuple_cat` only accepts tuples
D. 4

**Answer (B):** 3

**Why:** `tuple_cat` accepts tuples and pairs (and arrays) and flattens one level. The result concatenates one element, two elements and zero elements, giving 3. A pair is not kept as a single nested element.

### Question 4 [tricky] ([tuple.creation])

Which type does `decltype(std::forward_as_tuple(a, 1))` name, given `int a = 0;`?

A. `std::tuple<int, int>`
B. `std::tuple<int&, int&&>`
C. `std::tuple<int&, const int&>`
D. `std::tuple<int&, int&>`

**Answer (B):** `std::tuple<int&, int&&>`

**Why:** `forward_as_tuple` takes forwarding references and builds a tuple of the deduced types, `Types&&...`. For the lvalue `a` that is `int&` and for the prvalue `1` it is `int&&`. Nothing is copied, which is why storing the result can leave a dangling reference to the temporary.

### Question 5 [tricky] ([pairs], [tuple.assign])

What does this program print?

```cpp
#include <utility>
#include <cstdio>

int main() {
  int a = 1, b = 2;
  std::pair<int&, int> p{a, 0};
  std::pair<int&, int> q{b, 0};
  p = q;
  b = 7;
  std::printf("%d %d %d\n", a, b, p.first);
}
```

A. `1 7 7`, because `p.first` now refers to `b`
B. `1 7 1`
C. `2 7 2`
D. Ill-formed: a pair holding a reference is not assignable

**Answer (C):** `2 7 2`

**Why:** References cannot be rebound, so the pair's assignment operator assigns the referred-to objects: `a = b` copies 2 into `a`. `p.first` still names `a`, so after `b = 7` the output is `2 7 2`. The tempting first option treats the assignment as rebinding.

### Question 6 [tricky] ([tuple.creation])

Which of these `static_assert`s fails?

```cpp
#include <tuple>
#include <functional>
#include <type_traits>

int a = 0;
const int b = 0;

static_assert(std::is_same_v<decltype(std::make_tuple("hi")), std::tuple<const char*>>);
static_assert(std::is_same_v<decltype(std::make_tuple(std::ref(a))), std::tuple<int&>>);
static_assert(std::is_same_v<decltype(std::make_tuple(b)), std::tuple<const int>>);
static_assert(std::is_same_v<decltype(std::make_tuple(std::cref(b))), std::tuple<const int&>>);

int main() {}
```

A. The first: the literal gives `tuple<char[3]>`
B. The second: `make_tuple` never produces reference elements
C. The third
D. The fourth

**Answer (C):** The third

**Why:** `make_tuple` stores `decay_t` of each argument, which strips const, so `make_tuple(b)` is `tuple<int>`, not `tuple<const int>`, and the third assertion makes the program ill-formed. The array decays to a pointer, and `reference_wrapper` arguments are unwrapped to references, so the other three assertions hold.

### Question 7 [standardese] ([tuple.rel], [cmp.common])

In C++20, what is the type of `std::tuple<int, double>{} <=> std::tuple<int, double>{}`?

A. `std::strong_ordering`, because `int` is compared first
B. `std::weak_ordering`
C. `std::partial_ordering`
D. It is ill-formed: `tuple` has no `operator<=>`

**Answer (C):** `std::partial_ordering`

**Why:** The result of tuple's `operator<=>` is the common comparison category of the element comparisons. `double` compares as `partial_ordering` because of NaN, and the common category of `strong_ordering` and `partial_ordering` is `partial_ordering`. The category does not depend on which element decides at run time.

### Question 8 [standardese] ([pairs.pair])

`Pinned` has a constructor `Pinned(int, int)` and a deleted copy constructor. Is the `emplace` call below well-formed?

```cpp
#include <map>
#include <tuple>
#include <utility>

struct Pinned {
  Pinned(int, int) {}
  Pinned(const Pinned&) = delete;
};

int main() {
  std::map<int, Pinned> m;
  m.emplace(std::piecewise_construct,
            std::forward_as_tuple(1),
            std::forward_as_tuple(2, 3));
}
```

A. Ill-formed: `emplace` needs a copy or move constructor for `Pinned`
B. Well-formed: each member of the pair is built in place from its own tuple of arguments
C. Well-formed only if `forward_as_tuple` is replaced by `make_tuple`
D. Ill-formed: `piecewise_construct` is only for `unordered_map`

**Answer (B):** Well-formed: each member of the pair is built in place from its own tuple of arguments

**Why:** `pair<const int, Pinned>` has a piecewise constructor taking one argument tuple per member. It forwards each tuple's elements to the corresponding member's constructor, so `Pinned` is constructed directly from `(2, 3)` and is never copied or moved. `emplace(1, 2, 3)` would fail because the pair has no such three-argument constructor.

# Callable wrappers

> std::function, move_only_function, copyable_function and function_ref are four answers to the question of how to store or pass a callable of unknown type. They differ in ownership, copyability and in whether the call signature can say const, noexcept or a reference qualifier. The invoke rules and the binders sit underneath all of them.

- **Source:** C++ Atlas (https://cppatlas.com/topics/callable-wrappers)
- **Track:** Library utilities
- **Estimated reading time:** 15 minutes
- **ISO C++ clauses:** [func.def] (https://eel.is/c++draft/func.def), [func.require] (https://eel.is/c++draft/func.require), [func.invoke] (https://eel.is/c++draft/func.invoke), [func.bind] (https://eel.is/c++draft/func.bind), [func.bind.partial] (https://eel.is/c++draft/func.bind.partial), [func.memfn] (https://eel.is/c++draft/func.memfn), [func.not.fn] (https://eel.is/c++draft/func.not.fn), [refwrap] (https://eel.is/c++draft/refwrap), [func.wrap] (https://eel.is/c++draft/func.wrap)
- **cppreference links:** [std::function](https://en.cppreference.com/w/cpp/utility/functional/function), [std::move_only_function](https://en.cppreference.com/w/cpp/utility/functional/move_only_function), [std::copyable_function](https://en.cppreference.com/w/cpp/utility/functional/copyable_function), [std::function_ref](https://en.cppreference.com/w/cpp/utility/functional/function_ref), [std::invoke](https://en.cppreference.com/w/cpp/utility/functional/invoke), [std::bind](https://en.cppreference.com/w/cpp/utility/functional/bind), [std::bind_front, std::bind_back](https://en.cppreference.com/w/cpp/utility/functional/bind_front), [std::reference_wrapper](https://en.cppreference.com/w/cpp/utility/functional/reference_wrapper), [std::mem_fn](https://en.cppreference.com/w/cpp/utility/functional/mem_fn), [std::not_fn](https://en.cppreference.com/w/cpp/utility/functional/not_fn)
- **Prerequisites:** lambdas, copy-and-move, forwarding-references-and-perfect-forwarding

## The one idea

Every lambda has its own unnamed type, so two lambdas with the same signature cannot be stored in the same variable. A function template can accept any of them, but a data member, a container element or a virtual function signature needs one fixed type. A callable wrapper is that type. It erases the concrete callable type and keeps only the call signature, at the price of an indirect call and, sometimes, an allocation.

> **Mental model.** A wrapper is a small object holding a pointer to a type-specific table of functions (call, copy, move, destroy) and the callable itself. The four standard wrappers differ in which of those operations they support, and who owns the callable.

| Wrapper | Owns the callable | Copyable | Signature can carry | Standard |
| --- | --- | --- | --- | --- |
| `function` | yes | yes, so target must be copyable | return and parameters only | C++11 |
| `move_only_function` | yes | no, move only | `const`, `&`, `&&`, `noexcept` | C++23 |
| `copyable_function` | yes | yes | `const`, `&`, `&&`, `noexcept` | C++26 |
| `function_ref` | no, it refers | yes, trivially | `const`, `noexcept` | C++26 |

## std::function

`std::function<R(Args...)>` stores a copy of any callable that is copy constructible and invocable with those arguments, converting the result to `R`. It is copyable itself, which is exactly why the target must be copyable: a `std::function` holding a lambda that captured a `unique_ptr` does not compile.

An empty `function` (default constructed, or constructed from a null function pointer) throws `bad_function_call` when called, and converts to `false`.

```cpp
#include <functional>
#include <cstdio>

int main() {
  std::function<void()> f;
  try { f(); } catch (const std::bad_function_call&) { std::puts("empty"); }

  std::function<int()> counter = [n = 0]() mutable { return ++n; };
  const auto& view = counter;                    // a const reference to the wrapper
  std::printf("%d %d\n", view(), view());        // 1 2: the mutable lambda changed state
}
```

The second half of that program is the const-correctness hole. `function::operator()` is `const`, yet it calls the stored object as a non-const lvalue, so a `mutable` lambda mutates through a const reference. Nothing in the type warns you, and concurrent calls through const references race on the target even though every handle looks const.

The standard does not require `function` to avoid heap allocation for small targets. It only says implementations are encouraged to avoid it for small callables, and guarantees no exceptions when constructing from a function pointer or a `reference_wrapper`. Real libraries keep a small inline buffer of a few pointers; how large it is differs between them, so a lambda that captures a lot may allocate on one library and not on another.

`target<T>()` returns a pointer to the held object if its type is exactly `T`, and null otherwise. It is rarely worth using; if you need to know what is inside, a wrapper is the wrong tool.

## move_only_function and the qualified signature

C++23 added `std::move_only_function` for the cases `function` rejects. It owns a callable that may be move only, such as a lambda holding a `unique_ptr`, and the wrapper itself can only be moved. It also fixes the hole: the cv-qualifiers, ref-qualifier and `noexcept` of the signature become those of its `operator()`, and the stored callable must be invocable with exactly that qualification.

```cpp
#include <functional>
#include <memory>
#include <cstdio>

int main() {
  auto p = std::make_unique<int>(4);
  std::move_only_function<int()> a = [p = std::move(p)] { return *p; };   // OK: move only target
  std::printf("%d\n", a());

  std::move_only_function<int() const> b = [] { return 1; };              // OK: callable const
  // std::move_only_function<int() const> c = [n = 0]() mutable { return ++n; };
  //   ill-formed: a mutable lambda is not invocable as const
  std::printf("%d\n", b());
}
```

Calling an empty `move_only_function` is undefined behavior, not an exception, so test it before calling when it can be empty. It is also the right wrapper for a task queue: queue elements are invoked once and moved, never copied.

> **Standardese.** In [func.wrap], the signature template parameter of `move_only_function` is `R(Args...) cv ref noexcept(noex)`. The target must be invocable with that qualification: with a `const` in the signature it is called as a const object, with `&` as an lvalue, with `&&` as an rvalue, and with no ref-qualifier it must work as both an lvalue and an rvalue. The wrapper's own `operator()` carries the same qualifiers.

### C++26: copyable_function and function_ref

`std::copyable_function` is `move_only_function` with copyability: same signature qualifiers, same undefined behavior when empty, but the target must be copy constructible, and the wrapper is copyable. It replaces `function` where you want the const-correct signature.

`std::function_ref` is a non-owning view of a callable: trivially copyable, typically two pointers in size, and it never allocates. It suits a parameter that is only used during the call. The danger is the same as for `string_view`: if the referenced callable dies first, the call is undefined behavior, and binding it to a temporary lambda and keeping it past the statement is the classic mistake.

```cpp
#include <functional>
#include <cstdio>

#if defined(__cpp_lib_function_ref)
int apply_twice(std::function_ref<int(int)> f, int x) { return f(f(x)); }
#else
template <class F> int apply_twice(F f, int x) { return f(f(x)); }
#endif

int main() {
  int k = 5;
  std::printf("%d\n", apply_twice([&](int a) { return a + k; }, 1));  // 11
}
```

Both are C++26 library features. GCC 16 provides them in `-std=c++26` mode, while the libc++ shipped with the Clang used to cross-check this page does not yet, so check your library.

## std::invoke and the INVOKE rules

Every wrapper, `std::thread`, `std::apply` and the binders define what it means to call something by a single rule, called INVOKE. For an ordinary callable, it is just `f(args...)`. For a pointer to member, the first argument is the object, which may be given as an object, a reference, a pointer or smart pointer, or a `reference_wrapper`.

```cpp
#include <functional>
#include <memory>
#include <cstdio>

struct S {
  int val = 3;
  int add(int a) const { return a + val; }
};

int main() {
  S s;
  std::printf("%d %d %d\n",
    std::invoke(&S::add, s, 1),                // member function on an object
    std::invoke(&S::add, &s, 2),               // ... on a pointer
    std::invoke(&S::val, std::ref(s)));        // data member through reference_wrapper
  static_assert(std::is_same_v<std::invoke_result_t<int S::*, S>, int&&>);   // rvalue object
}
```

A pointer to a data member behaves like a function from object to member, and the value category follows the object: invoked on an rvalue it gives an rvalue reference, on a const lvalue a const lvalue reference. `std::invoke_r` (C++23) additionally converts the result. Generic code that calls user callables should use `std::invoke`, since `f(args...)` fails for member pointers.

## bind, bind_front, bind_back and lambdas

`std::bind` copies the callable and the bound arguments, and `_1`, `_2` placeholders select the call arguments. Bound arguments are stored by decay copy: `std::ref` is how you ask for a reference. Extra call arguments are silently discarded, and a nested bind expression as an argument is itself evaluated.

```cpp
#include <functional>
#include <cstdio>

int sub(int a, int b) { return a - b; }

int main() {
  using namespace std::placeholders;
  int x = 1;
  auto by_value = std::bind(sub, x, 0);
  auto by_ref   = std::bind(sub, std::ref(x), 0);
  x = 5;
  std::printf("%d %d\n", by_value(), by_ref());       // 1 5
  std::printf("%d\n", std::bind(sub, _2, _1)(1, 10)); // 9: sub(10, 1)
}
```

`bind_front(f, args...)` and `bind_back(f, args...)` (C++20 and C++23) bind only leading or trailing arguments, forward everything else, and propagate the callable's noexcept-ness and value categories. They have no placeholders, no nested-bind magic, and no silent argument dropping. With `bind_front(sub, 10)(3)` giving `sub(10, 3)` and `bind_back(sub, 10)(3)` giving `sub(3, 10)`.

Prefer a lambda over all of them. A lambda says what it captures, works with overloaded names and templates, and is visible to the optimizer. `bind` struggles with overloaded functions, because the name does not pick an overload by itself. Reach for `bind_front` when you really need partial application of a callable you do not want to wrap, and for `bind` mainly in legacy code.

## reference_wrapper, mem_fn and not_fn

`std::reference_wrapper<T>` is a copyable, assignable object that refers to a `T`. Unlike a built-in reference, assignment *rebinds* it. `std::ref` and `std::cref` create one, and it is callable when `T` is.

```cpp
#include <functional>
#include <cstdio>

int main() {
  int a = 1, b = 2;
  std::reference_wrapper<int> r = a;
  r = b;                              // rebinds r to b; a is unchanged
  r.get() = 7;                        // writes b
  std::printf("%d %d\n", a, b);       // 1 7
}
```

`std::mem_fn(&S::add)` turns a member pointer into an ordinary callable object taking the object as its first argument, which is mostly useful when an API expects a plain callable and you have only a member pointer. `std::not_fn(f)` returns a callable that negates the result of `f` and forwards the arguments, replacing the removed `not1` and `not2`.

## Cost model

A call through any wrapper is an indirect call that the compiler usually cannot inline, so it costs a few nanoseconds and breaks optimization across the boundary. Constructing a `function`, `move_only_function` or `copyable_function` may allocate if the target does not fit the library's inline buffer; `function_ref` never allocates. A template parameter `F&&` has no wrapper cost at all but instantiates code per callable and cannot be stored in a member of fixed type.

A workable rule: take a template parameter or `function_ref` for a callable used during the call, store a `move_only_function` for a callable you keep, and use `function` or `copyable_function` only when the stored object must be copied.

## What to remember

- A wrapper erases the callable's type and keeps its signature, at the cost of an indirect call and a possible allocation.
- `std::function` requires a copyable target, throws `bad_function_call` when empty, and its `const operator()` can still mutate a `mutable` target.
- `move_only_function` (C++23) accepts move-only targets and puts `const`, `&`, `&&` and `noexcept` in the signature; calling it empty is undefined behavior.
- `copyable_function` and `function_ref` are C++26; the second is a non-owning view and can dangle.
- INVOKE handles member pointers with objects, pointers and `reference_wrapper`; generic code should call `std::invoke`.
- `bind` stores decayed copies, so use `std::ref` for references; `bind_front` and `bind_back` have no placeholders; a lambda is usually clearer.
- `reference_wrapper` rebinds on assignment.

## Concept Map Outline

- **Callable wrappers:** Type-erased holders for callables, plus the invoke rules and binders beneath them.
  - **std::function:** The C++11 copyable wrapper that keeps only the call signature.
    - **Copyable target:** The stored callable must be copy constructible, so move-only closures are rejected.
    - **Empty call:** Calling an empty function throws bad_function_call.
    - **Const hole:** operator() is const but calls the target non-const, so a mutable lambda mutates.
    - **Small buffer:** Only encouraged by the standard; large targets may allocate, and the limit varies by library.
  - **Qualified signatures:** Newer wrappers put const, reference and noexcept qualifiers in the signature.
    - **move_only_function:** C++23 owning wrapper that is move only and accepts move-only targets.
    - **copyable_function:** C++26 copyable counterpart with the same qualifier support.
    - **Empty call is UB:** Unlike function, calling an empty one of these is undefined behavior.
    - **Const-correct:** A const in the signature rejects a mutable target at construction.
  - **function_ref:** C++26 non-owning view of a callable.
    - **No allocation:** It stores a reference and a thunk, is trivially copyable, and never allocates.
    - **Dangling risk:** Calling it after the target is destroyed is undefined behavior, as with string_view.
  - **invoke rules:** INVOKE is the single definition of calling, used throughout the library.
    - **Member pointers:** The first argument may be an object, reference, pointer, smart pointer or reference_wrapper.
    - **Value category:** A data member pointer yields a result whose category follows the object.
  - **Binders:** Ways to fix some arguments of a callable.
    - **bind:** Stores decayed copies, uses placeholders, and drops extra call arguments.
    - **bind_front and bind_back:** Bind leading or trailing arguments with perfect forwarding and no placeholders.
    - **Lambdas:** Usually clearer and more optimizable than any binder.
  - **Helpers and cost:** Small adapters, and what the wrappers cost.
    - **reference_wrapper:** A copyable reference that rebinds on assignment; made by ref and cref.
    - **mem_fn and not_fn:** mem_fn adapts member pointers; not_fn negates a callable's result.
    - **Cost model:** An indirect call that rarely inlines, plus a possible allocation on construction.

## Standardese Quiz Questions

### Question 1 [warmup] ([func.wrap.func.inv])

What does this program print?

```cpp
#include <functional>
#include <cstdio>

int main() {
  std::function<int(int)> f;
  try {
    std::printf("%d\n", f(1));
  } catch (const std::bad_function_call&) {
    std::puts("empty");
  }
}
```

A. `0`
B. Undefined behavior: the wrapper holds no target
C. `empty`
D. It does not compile: `f` has no initializer

**Answer (C):** `empty`

**Why:** Calling an empty `std::function` throws `std::bad_function_call`, so the handler prints `empty`. The tempting alternative, undefined behavior, is the rule for the newer `move_only_function` and `copyable_function`, which deliberately do not check.

### Question 2 [warmup] ([func.wrap.func.con])

Is this program well-formed in C++23?

```cpp
#include <functional>
#include <memory>

int main() {
  auto p = std::make_unique<int>(1);
  std::function<void()> f = [p = std::move(p)] {};
}
```

A. No: the target of a `std::function` must be copy constructible
B. Yes: the lambda is moved into the wrapper
C. Yes, but copying `f` later throws
D. Yes: only `std::bind` requires copyable callables

**Answer (A):** No: the target of a `std::function` must be copy constructible

**Why:** `std::function` is itself copyable, so it requires its target to be copy constructible, and a closure holding a `unique_ptr` is not, so the program is ill-formed. The wrapper to use is `std::move_only_function`, added in C++23.

### Question 3 [warmup] ([func.bind.place])

What does this program print?

```cpp
#include <functional>
#include <cstdio>

int sub(int a, int b) { return a - b; }

int main() {
  using namespace std::placeholders;
  auto g = std::bind(sub, _2, _1);
  std::printf("%d\n", g(1, 10));
}
```

A. `-9`
B. `1`
C. It does not compile: `g` is called with the arguments in the wrong order
D. `9`

**Answer (D):** `9`

**Why:** `_1` and `_2` name the first and second argument of the call to `g`. Here the bound call is `sub(_2, _1)`, which with arguments `(1, 10)` is `sub(10, 1)`, giving 9. The placeholders choose which call argument goes where; they are not positions in `sub`.

### Question 4 [tricky] ([func.wrap.func.inv])

What does this program print?

```cpp
#include <functional>
#include <cstdio>

int main() {
  std::function<int()> f = [n = 0]() mutable { return ++n; };
  const auto& cf = f;
  int a = cf();
  int b = cf();
  std::printf("%d %d\n", a, b);
}
```

A. `1 1`: a const wrapper calls a copy of the lambda
B. `1 2`
C. Ill-formed: a `mutable` lambda cannot be called through a const `function`
D. Undefined behavior: the lambda is modified through a const object

**Answer (B):** `1 2`

**Why:** `std::function::operator()` is a const member function, but it calls the stored callable as a non-const lvalue. The mutable lambda therefore updates its own state on each call and the output is `1 2`. This is the const-correctness hole that `move_only_function<int() const>` and `copyable_function<int() const>` close by refusing such a target.

### Question 5 [tricky] ([func.bind.bind])

What does this program print?

```cpp
#include <functional>
#include <cstdio>

int sub(int a, int b) { return a - b; }

int main() {
  int x = 1;
  auto v = std::bind(sub, x, 0);
  auto r = std::bind(sub, std::ref(x), 0);
  x = 5;
  std::printf("%d %d\n", v(), r());
}
```

A. `1 5`
B. `5 5`
C. `1 1`
D. `5 1`

**Answer (A):** `1 5`

**Why:** `std::bind` stores a decayed copy of each bound argument made at the time of the `bind` call, so `v` holds 1 regardless of later changes to `x`. Wrapping the argument in `std::ref` stores a `reference_wrapper`, which is unwrapped on the call, so `r` sees 5.

### Question 6 [tricky] ([refwrap.assign])

What does this program print?

```cpp
#include <functional>
#include <cstdio>

int main() {
  int a = 1, b = 2;
  std::reference_wrapper<int> r = a;
  r = b;
  r.get() = 7;
  std::printf("%d %d\n", a, b);
}
```

A. `2 2`
B. `7 2`
C. `1 7`
D. `2 7`

**Answer (C):** `1 7`

**Why:** Unlike a built-in reference, assigning to a `reference_wrapper` rebinds it, so `r = b` makes `r` refer to `b` and leaves `a` untouched. The next statement writes 7 through `r` into `b`, so the output is `1 7`. The tempting `2 7` reads the assignment as copying the value into `a`.

### Question 7 [standardese] ([func.wrap.move.ctor])

Is this program well-formed in C++23?

```cpp
#include <functional>

int main() {
  std::move_only_function<int() const> f = [n = 0]() mutable { return ++n; };
}
```

A. Yes: the wrapper copies the lambda and calls the copy
B. Yes: `mutable` lambdas are exempt from the check
C. Yes, and calling `f` is undefined behavior
D. No: the target must be invocable as a const object

**Answer (D):** No: the target must be invocable as a const object

**Why:** In `move_only_function<R(Args...) cv ref noexcept>` the qualifiers describe how the wrapper calls its target, and the constructor is constrained so the target must be invocable that way. A `mutable` lambda has a non-const call operator, so it cannot be called as `const`, the constructor is not viable, and the program is ill-formed. `std::function` would accept the same lambda.

### Question 8 [standardese] ([func.require], [func.invoke])

Given `struct S { int val; };`, which of these `static_assert`s fails in C++23?

```cpp
#include <functional>
#include <type_traits>

struct S { int val; };
using std::is_same_v;
using std::invoke_result_t;

static_assert(is_same_v<invoke_result_t<int S::*, S&>, int&>);
static_assert(is_same_v<invoke_result_t<int S::*, const S&>, const int&>);
static_assert(is_same_v<invoke_result_t<int S::*, S>, int>);
static_assert(is_same_v<invoke_result_t<int S::*, std::reference_wrapper<S>>, int&>);

int main() {}
```

A. The first: a data member pointer cannot be invoked
B. The third: invoking on an rvalue `S` yields `int&&`, not `int`
C. The second: constness is dropped
D. The fourth: `reference_wrapper` is not an object of class `S`

**Answer (B):** The third: invoking on an rvalue `S` yields `int&&`, not `int`

**Why:** INVOKE for a pointer to data member returns an expression whose value category follows the object: an lvalue object gives an lvalue, a const lvalue gives a const lvalue, and an rvalue object gives an xvalue, so the type is `int&&` and the third `static_assert` is ill-formed. A `reference_wrapper` argument is unwrapped by INVOKE, so the fourth assertion holds.

# chrono

> std::chrono puts the unit into the type. A duration is a count and a ratio, a time point is a duration since a clock's epoch, and a clock says where time points come from. The rules that matter are which conversions are implicit, what each clock promises, and how C++20 calendars and time zones handle dates that do not exist.

- **Source:** C++ Atlas (https://cppatlas.com/topics/chrono)
- **Track:** Library utilities
- **Estimated reading time:** 15 minutes
- **ISO C++ clauses:** [time.duration] (https://eel.is/c++draft/time.duration), [time.duration.cast] (https://eel.is/c++draft/time.duration.cast), [time.point] (https://eel.is/c++draft/time.point), [time.clock] (https://eel.is/c++draft/time.clock), [time.clock.system] (https://eel.is/c++draft/time.clock.system), [time.clock.steady] (https://eel.is/c++draft/time.clock.steady), [time.cal] (https://eel.is/c++draft/time.cal), [time.zone] (https://eel.is/c++draft/time.zone), [time.format] (https://eel.is/c++draft/time.format)
- **cppreference links:** [Date and time utilities](https://en.cppreference.com/w/cpp/chrono), [std::chrono::duration](https://en.cppreference.com/w/cpp/chrono/duration), [std::chrono::duration_cast](https://en.cppreference.com/w/cpp/chrono/duration/duration_cast), [std::chrono::time_point](https://en.cppreference.com/w/cpp/chrono/time_point), [std::chrono::system_clock](https://en.cppreference.com/w/cpp/chrono/system_clock), [std::chrono::steady_clock](https://en.cppreference.com/w/cpp/chrono/steady_clock), [std::chrono::year_month_day](https://en.cppreference.com/w/cpp/chrono/year_month_day), [std::chrono::zoned_time](https://en.cppreference.com/w/cpp/chrono/zoned_time), [std::chrono::utc_clock](https://en.cppreference.com/w/cpp/chrono/utc_clock)
- **Prerequisites:** integer-arithmetic-and-overflow, implicit-conversions

## The one idea

A time quantity in `<chrono>` is three separate ideas, each with its own type. A **duration** is a length of time: a count plus a unit. A **time point** is a position in time: a duration measured from a clock's epoch. A **clock** is a source of time points, and it fixes which epoch and which unit.

The point of splitting them is that mistakes become compile errors. You cannot pass a bare `5` where a duration is expected, you cannot add two positions in time, and you cannot subtract a steady-clock time from a system-clock time.

> **Mental model.** A duration is a number with a unit, a time point is a duration with an origin, and the compiler checks the unit and the origin on every operation.

## Durations

`std::chrono::duration<Rep, Period>` stores one value of type `Rep` and has a compile-time `Period`, a `std::ratio` giving seconds per tick. The standard aliases are `nanoseconds` through `hours`, and since C++20 also `days`, `weeks`, `months` and `years`; the last two are fixed average lengths, not calendar months. The standard requires only a minimum width for each rep: a signed integer of at least 64 bits for `nanoseconds`, and at least 35 bits for `seconds`.

The constructor from a count is `explicit`, so `std::chrono::milliseconds ms = 5;` does not compile. Literals live in `std::chrono_literals`: `5ms`, `2h`, `1.5s`.

### Implicit and explicit conversion

A conversion happens implicitly only if it cannot lose precision: either the destination rep is floating point, or the source period is an exact multiple of the destination period and both reps are integral. Everything else needs `duration_cast`.

```cpp
#include <chrono>
using namespace std::chrono;
using namespace std::chrono_literals;

int main() {
  milliseconds a = 2s;                      // OK: seconds to milliseconds is exact
  duration<double> b = 1500ms;              // OK: floating-point rep never truncates
  // seconds c = 1500ms;                    // ill-formed: would truncate
  seconds d = duration_cast<seconds>(1500ms);   // OK: explicit, truncates to 1s
  (void)a; (void)b; (void)d;
}
```

`duration_cast` truncates toward zero, which for negative values is not what most people expect. C++17 added `floor`, `ceil` and `round` for durations: `floor` goes toward negative infinity, `ceil` toward positive infinity, and `round` goes to the nearest, with ties to the even value.

```cpp
#include <chrono>
#include <cstdio>
using namespace std::chrono;
using namespace std::chrono_literals;

int main() {
  std::printf("%lld %lld\n",
    (long long)duration_cast<seconds>(-1500ms).count(),   // -1: toward zero
    (long long)floor<seconds>(-1500ms).count());          // -2: toward negative infinity
  std::printf("%lld %lld\n",
    (long long)round<seconds>(2500ms).count(),            // 2: tie goes to even
    (long long)round<seconds>(3500ms).count());           // 4
}
```

### Arithmetic

Adding or comparing two durations first converts both to their common type, the longest period that divides both. `2h + 30min` is therefore a `minutes` holding 150. Multiplying or dividing by a plain number keeps the unit: `1s / 2` is a `seconds` and, because the rep is integral, equals zero seconds. Dividing a duration by a duration gives a unitless number in the common rep, so `1500ms / 1s` is the integer 1, while `duration<double>(1500ms) / 1s` is 1.5. If you want a fraction of a unit, make the rep floating point first.

## Overflow in nanoseconds

Duration arithmetic is plain arithmetic on the rep, and for the standard aliases the rep is a signed integer, so overflow is undefined behavior. There is no saturation and no check.

The range is smaller than it looks. A 64-bit count of nanoseconds covers about 292 years in total, which is roughly the years 1678 to 2262 around the Unix epoch. Converting a large coarse duration to `nanoseconds` can overflow silently, and so can storing system time in `nanoseconds` far from 1970.

```cpp
#include <chrono>
using namespace std::chrono_literals;

constexpr std::chrono::nanoseconds bump(std::chrono::nanoseconds n) { return n + 1ns; }

constexpr auto fine = bump(0ns);                                // OK: 1ns
// constexpr auto bad = bump(std::chrono::nanoseconds::max());  // ill-formed: signed overflow
//                                                              // is not a constant expression
int main() { (void)fine; }
```

Constant evaluation rejects the overflow, which is a convenient way to check an assumption at compile time. At run time, the same expression is simply undefined behavior, so sanitizers and range checks are your only protection. The topic on integer arithmetic covers the general rules.

## Clocks and time points

A `time_point<Clock, Duration>` holds a duration since the clock's epoch. Subtracting two time points of the same clock gives a duration; adding a duration gives a time point; adding two time points does not compile; and time points of different clocks do not mix.

| Clock | Use it for | Notes |
| --- | --- | --- |
| `system_clock` | wall-clock time, calendar dates | can jump when the system time is adjusted; epoch is Unix time since C++20 |
| `steady_clock` | measuring intervals | never goes backwards; epoch is arbitrary, so values are meaningless alone |
| `high_resolution_clock` | rarely anything | the standard allows it to be an alias of another clock, and often is |
| `utc_clock` (C++20) | UTC including leap seconds | counts leap seconds, unlike `system_clock` |
| `tai_clock` (C++20) | atomic time | no leap seconds; epoch 1958-01-01 |
| `gps_clock` (C++20) | GPS time | no leap seconds; epoch 1980-01-06 |
| `file_clock` (C++20) | file timestamps | the clock behind `filesystem::file_time_type`; epoch unspecified |

`high_resolution_clock` is a trap rather than a tool. Depending on the library it is `system_clock`, `steady_clock`, or a separate clock. If it is the first, a timing measurement can run backwards when the system clock is corrected. Measure intervals with `steady_clock`.

```cpp
#include <chrono>
#include <cstdio>

int main() {
  auto start = std::chrono::steady_clock::now();
  // ... work ...
  auto elapsed = std::chrono::steady_clock::now() - start;   // a duration
  auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed);
  std::printf("%lld ms\n", static_cast<long long>(ms.count()));
}
```

The C++20 clocks convert to each other with `std::chrono::clock_cast`. The conversion between `system_clock` and `utc_clock` accounts for leap seconds, so the two differ by a whole number of seconds that grows over the years. The precision of `now()` and the duration type it returns are implementation choices, so write code that does not depend on either.

## Calendar types

C++20 added value types for the pieces of a date: `year`, `month`, `day`, `weekday`, and the combinations `year_month_day`, `year_month_weekday` and others. The `/` operator builds them, and the literals `2024y` and `15d` and the constants `January` to `December` make the code read like a date. The result is a plain value type with no clock and no time zone.

```cpp
#include <chrono>
#include <iostream>
using namespace std::chrono;

int main() {
  year_month_day a = 2024y / February / 29;     // valid: 2024 is a leap year
  year_month_day b = 2023y / February / 30;     // constructs fine, but not a real date
  std::cout << a.ok() << b.ok() << '\n';        // 10

  year_month_day c = 2024y / January / 31;
  c += months{1};                               // no clamping: this is February 31
  std::cout << c.ok() << ' ' << unsigned(c.day()) << '\n';   // 0 31

  auto end_of_feb = 2024y / February / last;    // year_month_day_last
  std::cout << unsigned(end_of_feb.day()) << '\n';   // 29
}
```

Constructing an invalid date is not an error; `ok()` tells you whether it is real. Month arithmetic keeps the day number and does not clamp, so `January 31 + 1 month` is `February 31`, which is invalid until you check it. Arithmetic on `month` and `weekday` alone wraps: `December + months{1}` is `January`. Always call `ok()` on dates that come from input or arithmetic.

> **Pitfall.** `2024/2/29` is integer division and gives `34`, not a date. At least one operand of the first `/` must be a `year`, `month` or `day` type, such as `2024y`.

The bridge to the rest of chrono is `sys_days`, a `time_point` on `system_clock` with a resolution of one day. A `year_month_day` converts to `sys_days` and back, and `sys_days` plus a number of `days` is ordinary time point arithmetic.

> **Standardese.** The conversion from `year_month_day` to `sys_days` in [time.cal.ymd.members] is specified for invalid days too, as long as the year and month are valid: the result is the first of the month plus the day number minus one. So `2023y/February/30` converts to the same `sys_days` as `2023y/March/2`. If the year or month is itself invalid, the result is unspecified.

## Time zones and zoned_time

A `sys_time` is UTC. A `local_time` is a time of day on a calendar with no zone attached, and it is deliberately a different type so you cannot mix them by accident. A `zoned_time` pairs a time zone with a point in time and can show it either way.

Time zones come from the IANA database, reached with `std::chrono::locate_zone("Asia/Kolkata")` or `current_zone()`. The library needs a time zone database at run time; where none is available, these calls can throw. Check that your platform ships one.

Going from UTC to local time always works. Going the other way can fail, because local time is not a one-to-one mapping. When clocks jump forward, a range of local times never happens, and when they jump back, a range happens twice. Constructing a `zoned_time` from such a local time throws `nonexistent_local_time` or `ambiguous_local_time`, unless you pass `choose::earliest` or `choose::latest` to resolve the overlap.

```cpp
#include <chrono>
#include <iostream>
#include <format>
using namespace std::chrono;
using namespace std::chrono_literals;

int main() {
  try {   // New York skips 02:00 to 03:00 on 2024-03-10
    zoned_time z{"America/New_York", local_days{2024y / March / 10} + 2h + 30min};
  } catch (const nonexistent_local_time&) {
    std::cout << "gap\n";
  }
  // 01:30 happens twice on 2024-11-03; ask for the first one
  zoned_time z{"America/New_York", local_days{2024y / November / 3} + 1h + 30min,
               choose::earliest};
  std::cout << std::format("{:%F %T %Z}\n", z);   // 2024-11-03 01:30:00 EDT
}
```

Store and compare instants in UTC (`sys_time`), and convert to a zone only to display. Adding `24h` to a `sys_time` moves exactly one physical day, while adding `days{1}` to a `local_time` moves to the same wall-clock time on the next date. Across a daylight saving change those are different instants.

## Formatting

With `std::format`, a duration prints its count followed by a unit suffix, and a time point or date prints as a date or date and time. A chrono format spec after the colon selects fields: `%F` is year-month-day, `%T` is hours, minutes and seconds, `%H:%M` is a clock time, and `%Z` is the zone abbreviation. The format-and-print topic covers the general machinery.

```cpp
#include <chrono>
#include <format>
#include <iostream>
using namespace std::chrono;
using namespace std::chrono_literals;

int main() {
  std::cout << std::format("{} {} {:%H:%M}\n", 90s, 1500ms, 90min);   // 90s 1500ms 01:30
  std::cout << std::format("{}\n", sys_days{2024y / February / 29});  // 2024-02-29
  std::cout << std::format("{:%F %T}\n", sys_seconds{1700000000s});   // 2023-11-14 22:13:20
}
```

## What the type system catches

- `milliseconds ms = 5;` fails because the count constructor is explicit, so you cannot lose the unit by accident.
- `seconds s = 1500ms;` and `milliseconds ms = 1.5s;` fail because they would truncate; spell the loss with `duration_cast`, `floor`, `ceil` or `round`.
- `sleep_for(5)` does not compile; a bare number has no unit.
- `now_a + now_b` for two time points does not compile, since adding two positions is meaningless, while `now_b - now_a` is a duration.
- A `steady_clock` time point cannot be compared to a `system_clock` one.
- A `local_time` cannot be passed where a `sys_time` is expected.

What the type system does not catch is overflow, an invalid date, and a local time that is not unique. Those need `ok()`, range reasoning and the `choose` argument.

## What to remember

- A duration is a count and a ratio, a time point is a duration from an epoch, and a clock supplies the epoch and the unit.
- Implicit duration conversions must be lossless; everything else uses `duration_cast` (toward zero), `floor`, `ceil` or `round` (ties to even).
- The common type of two durations is the finer one, so `2h + 30min` is `minutes{150}`; integer division by a number or another duration truncates.
- Duration overflow on a signed rep is undefined behavior; 64-bit nanoseconds span about 292 years.
- Use `steady_clock` to measure intervals; `high_resolution_clock` may be an alias of another clock, and `system_clock` can jump.
- C++20 adds `utc_clock` with leap seconds, `tai_clock`, `gps_clock` and `file_clock`, with `clock_cast` between them.
- Calendar values can be constructed invalid; check `ok()`. Month arithmetic does not clamp the day.
- `year_month_day` to `sys_days` normalizes an out-of-range day when the year and month are valid.
- `zoned_time` throws for a nonexistent local time and for an ambiguous one unless `choose` says which; store UTC and convert to a zone only to display.

## Concept Map Outline

- **chrono:** Durations, time points and clocks with units in the type, plus C++20 calendars and time zones.
  - **Durations:** A count of type rep and a compile-time period in seconds.
    - **Implicit conversion:** Allowed only when lossless: to a finer integer unit or to a floating-point rep.
    - **duration_cast:** Explicit conversion that truncates toward zero, even for negative values.
    - **floor ceil round:** C++17 helpers: round goes to nearest and breaks ties toward the even value.
    - **Common type:** Mixed arithmetic uses the finer unit, so 2h + 30min is minutes{150}.
    - **Division:** Duration divided by duration is a unitless number, and integer reps truncate.
  - **Overflow:** Duration arithmetic does not check for overflow.
    - **Signed rep:** Overflow of the signed count is undefined behavior, with no saturation.
    - **Nanosecond range:** A 64-bit count of nanoseconds spans only about 292 years.
    - **Constant evaluation:** A constexpr overflow is rejected, which makes a handy compile-time check.
  - **Clocks and time points:** A time point is a duration since a clock's epoch.
    - **system_clock:** Wall-clock time that can jump; its epoch is Unix time since C++20.
    - **steady_clock:** Monotonic and the right clock for measuring intervals.
    - **high_resolution_clock:** May be an alias of system_clock or steady_clock, so prefer the other two.
    - **C++20 clocks:** utc_clock counts leap seconds; tai_clock and gps_clock do not; file_clock has an unspecified epoch.
    - **Time point arithmetic:** point minus point is a duration; point plus point does not compile.
  - **Calendar types:** C++20 value types for year, month, day and weekday.
    - **Slash syntax:** 2024y/February/29 builds a date; plain 2024/2/29 is integer division.
    - **ok():** Invalid dates such as February 30 can be constructed, so check ok().
    - **Month arithmetic:** Adding months keeps the day without clamping, so January 31 plus a month is invalid.
    - **sys_days:** Day-precision system time point; an out-of-range day in a valid month normalizes.
  - **Time zones:** The IANA database reached through zoned_time.
    - **sys vs local:** sys_time is UTC and local_time has no zone, and they are distinct types.
    - **Gap:** A nonexistent local time makes the zoned_time constructor throw nonexistent_local_time.
    - **Overlap:** An ambiguous local time throws ambiguous_local_time unless choose is given.
  - **Formatting:** std::format understands durations, time points and dates.
    - **Duration suffix:** A duration prints its count followed by a unit suffix such as s or ms.
    - **Chrono specs:** Specs such as %F, %T, %H:%M and %Z select the fields to print.

## Standardese Quiz Questions

### Question 1 [warmup] ([time.duration.nonmember])

What does this program print?

```cpp
#include <chrono>
#include <iostream>
using namespace std::chrono_literals;

int main() {
  auto d = 2h + 30min;
  std::cout << d.count() << '\n';
}
```

A. `32`
B. `150`
C. `2.5`
D. `2`

**Answer (B):** `150`

**Why:** Adding durations converts both to their common type, the coarsest unit that represents both exactly, which here is `minutes`. So `2h` becomes 120 minutes and the sum is `minutes{150}`. Adding the raw counts, 2 and 30, would ignore the units, which the type system prevents.

### Question 2 [warmup] ([time.duration.cons])

Which declaration does not compile?

```cpp
#include <chrono>
using namespace std::chrono;
using namespace std::chrono_literals;

int main() {
  milliseconds a = 2s;                          // (1)
  duration<double> b = 1500ms;                  // (2)
  seconds c = 1500ms;                           // (3)
  seconds d = duration_cast<seconds>(1500ms);   // (4)
}
```

A. (1)
B. (2)
C. (3)
D. (4)

**Answer (C):** (3)

**Why:** A duration converts implicitly only when no precision can be lost: to a finer integer unit, or to any floating-point rep. Converting `1500ms` to integer `seconds` would drop 500 ms, so it needs `duration_cast`, which is why (3) is ill-formed and (4) is fine.

### Question 3 [warmup] ([time.duration.cast])

What does this program print?

```cpp
#include <chrono>
#include <iostream>
using namespace std::chrono;
using namespace std::chrono_literals;

int main() {
  std::cout << duration_cast<seconds>(-1500ms).count() << ' '
            << floor<seconds>(-1500ms).count() << '\n';
}
```

A. `-1 -2`
B. `-2 -2`
C. `-1 -1`
D. `-2 -1`

**Answer (A):** `-1 -2`

**Why:** `duration_cast` converts the representation by truncating toward zero, so -1500 ms becomes -1 s. `floor` rounds toward negative infinity and gives -2 s. For positive values the two agree, which is why the difference is easy to miss.

### Question 4 [tricky] ([time.cal.ymd.nonmembers])

What does this program print?

```cpp
#include <chrono>
#include <iostream>
using namespace std::chrono;

int main() {
  year_month_day d = 2024y / January / 31;
  d += months{1};
  std::cout << d.ok() << ' ' << unsigned(d.day()) << '\n';
}
```

A. `1 29`: the day is clamped to the end of February
B. `1 31`
C. It throws, because February 31 does not exist
D. `0 31`

**Answer (D):** `0 31`

**Why:** Adding months to a `year_month_day` changes the month and keeps the day number. The result is February 31, 2024, which is a representable but invalid date, so `ok()` is false and `day()` is still 31. Nothing clamps and nothing throws; you must call `ok()` and decide what to do.

### Question 5 [tricky] ([time.duration.nonmember])

What does this program print?

```cpp
#include <chrono>
#include <iostream>
using namespace std::chrono;
using namespace std::chrono_literals;

int main() {
  std::cout << 1500ms / 1s << ' '
            << duration<double>(1500ms) / 1s << '\n';
}
```

A. `1.5 1.5`
B. `1 1.5`
C. `1500 1.5`
D. `1 1`

**Answer (B):** `1 1.5`

**Why:** Dividing one duration by another converts both to their common type and divides the counts in the common rep. For `1500ms / 1s` the rep is integral, so the quotient is 1500 / 1000, which is 1. When one operand has a `double` rep, the common rep is `double` and the quotient is 1.5.

### Question 6 [tricky] ([expr.pre], [time.duration.nonmember])

Is this program well-formed in C++23?

```cpp
#include <chrono>
using namespace std::chrono_literals;

constexpr auto t = std::chrono::nanoseconds::max() + 1ns;

int main() { (void)t; }
```

A. Yes: `t` wraps around to `nanoseconds::min()`
B. Yes: duration arithmetic saturates at `max()`
C. No: the addition overflows the signed representation, which is not a constant expression
D. Yes, but `t` has an unspecified value

**Answer (C):** No: the addition overflows the signed representation, which is not a constant expression

**Why:** The representation of `nanoseconds` is a signed integer, and duration addition is ordinary integer addition on it, so exceeding the maximum is signed overflow, which is undefined behavior. A `constexpr` initializer must be a constant expression, and undefined behavior is not one, so the program is ill-formed and the compiler rejects it. At run time the same overflow would silently be undefined behavior; there is no saturation or wraparound guarantee.

### Question 7 [standardese] ([time.cal.ymd.members])

What does this program print in C++20 or later?

```cpp
#include <chrono>
#include <iostream>
using namespace std::chrono;

int main() {
  year_month_day d = 2023y / February / 30;
  std::cout << d.ok() << (sys_days{d} == sys_days{2023y / March / 2}) << '\n';
}
```

A. `00`: an invalid date has no `sys_days` value
B. `11`
C. `10`
D. `01`

**Answer (D):** `01`

**Why:** February 30 is not a valid date, so `ok()` is false. The conversion to `sys_days` is nonetheless specified when the year and month are valid: it gives the first of the month plus the day number minus one. For February 2023 that is March 2, so the comparison is true and the output is `01`. Only an invalid year or month leaves the result unspecified.

### Question 8 [standardese] ([time.zone.zonedtime.ctor], [time.zone.exception.nonexist])

In the `America/New_York` zone, clocks went from 02:00 to 03:00 on 2024-03-10. What does the standard specify for this program, assuming a time zone database is available?

```cpp
#include <chrono>
#include <iostream>
using namespace std::chrono;
using namespace std::chrono_literals;

int main() {
  try {
    zoned_time z{"America/New_York", local_days{2024y / March / 10} + 2h + 30min};
    std::cout << z << '\n';
  } catch (const nonexistent_local_time&) {
    std::cout << "gap\n";
  }
}
```

A. It prints `gap`: constructing a `zoned_time` from a nonexistent local time throws
B. It prints `2024-03-10 03:30:00 EDT`: the time is moved forward by the length of the gap
C. It prints `2024-03-10 01:30:00 EST`: the earlier offset is used
D. Undefined behavior: the local time does not exist

**Answer (A):** It prints `gap`: constructing a `zoned_time` from a nonexistent local time throws

**Why:** A local time inside a daylight saving gap maps to no instant. When the `zoned_time` constructor has to pick an instant from such a `local_time` and no `choose` argument was given, it throws `nonexistent_local_time`; the two silent options in the other answers are not behaviors the library provides. The ambiguous case, an hour that occurs twice when clocks go back, throws `ambiguous_local_time` unless `choose::earliest` or `choose::latest` is passed.

# std::format and std::print

> std::format replaces printf and iostream formatting with a type-safe format string that is checked at compile time and extended through formatter specializations. C++23 adds range and tuple formatting and std::print, which writes directly to a stream with Unicode awareness.

- **Source:** C++ Atlas (https://cppatlas.com/topics/format-and-print)
- **Track:** Library utilities
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [format.string] (https://eel.is/c++draft/format.string), [format.string.std] (https://eel.is/c++draft/format.string.std), [format.functions] (https://eel.is/c++draft/format.functions), [format.formatter.spec] (https://eel.is/c++draft/format.formatter.spec), [format.range] (https://eel.is/c++draft/format.range), [format.tuple] (https://eel.is/c++draft/format.tuple), [print.fun] (https://eel.is/c++draft/print.fun)
- **cppreference links:** [std::format](https://en.cppreference.com/w/cpp/utility/format/format), [Standard format specification](https://en.cppreference.com/w/cpp/utility/format/spec), [std::formatter](https://en.cppreference.com/w/cpp/utility/format/formatter), [std::vformat](https://en.cppreference.com/w/cpp/utility/format/vformat), [std::runtime_format](https://en.cppreference.com/w/cpp/utility/format/runtime_format), [std::format_to_n](https://en.cppreference.com/w/cpp/utility/format/format_to_n), [std::print](https://en.cppreference.com/w/cpp/io/print), [std::format_error](https://en.cppreference.com/w/cpp/utility/format/format_error)
- **Prerequisites:** variadic-templates-and-fold-expressions, concepts-and-constraints, strings-and-string-view

## The one idea

A format string is a tiny program with two kinds of parts: literal text, and replacement fields in braces. Each replacement field names an argument and hands a format specification to a `std::formatter<T>` for that argument's type. The formatter has two jobs: `parse` reads the specification and `format` writes the result. Everything in the library, from `{:>8.3f}` to a range of tuples, is built from that one handshake.

Two design decisions set `std::format` apart from `printf` and iostreams. The format string is a `consteval` constructor argument, so errors in it are compile errors. And formatting is separated from output: `std::format` builds a string, `std::format_to` writes through an iterator, `std::print` writes to a stream, and all three share the same formatters.

> **Mental model.** `std::format(fmt, args...)` first checks `fmt` against the argument types at compile time, then type-erases the arguments and runs each formatter over its own piece of the string.

## The replacement field and the standard spec

A replacement field is `{`, an optional argument index, an optional `:` followed by a specification, and `}`. Write `{{` and `}}` for literal braces. Indices must be all present or all absent: mixing `{}` with `{0}` is an error.

For built-in types the specification has a fixed order: fill and align, sign, `#`, `0`, width, precision, `L`, then type.

```cpp
#include <format>
#include <print>

int main() {
  std::println("[{:*^9}]", "mid");            // [***mid***]  fill '*', centered
  std::println("[{:>8.3f}]", 3.14159);        // [   3.142]
  std::println("{:+d} {:#x} {:#010b}", 5, 255, 5);  // +5 0xff 0b00000101
  std::println("{1} {0} {1}", "a", "b");      // b a b
  std::println("[{:{}}]", 7, 5);              // [    7]  width from argument 1
  std::println("{:.{}f}", 3.14159, 2);        // 3.14
}
```

Defaults differ by type. Numbers align right and strings align left, so `{:5}` pads `42` on the left and `"ab"` on the right. Precision on a string truncates it, and on a floating-point value it counts digits after the point for `f` and `e`. Width and precision can come from another argument with a nested `{}`, but that argument must be a standard integer type and not negative, otherwise `format_error` is thrown.

Details that surprise people:

- `bool` prints as `true` or `false` by default, and as a number with `d`. A `char` prints as a character by default and as a number with `d`. Integers accept `c` to print as a character.
- With `#`, the width includes the `0x` or `0b` prefix, and the `0` option inserts zeros after the prefix and sign.
- The `0` option is ignored for infinity and NaN, which are padded with spaces. It is also ignored when an alignment is given.
- Pointers print through `{}` or `{:p}` as a `0x` address; only `void*`, `const void*` and `nullptr_t` are formattable, not arbitrary object pointers.
- Floating-point output with no type letter is the shortest representation that round-trips, as `std::to_chars` would produce.

> **Standardese.** [format.string.std] defines the grammar for the standard specifiers, and says the padding width is measured in estimated display columns, not bytes. For a Unicode string, wide East Asian characters count as two columns.

## Compile-time checking, `vformat`, and runtime strings

The first parameter of `std::format` is a `std::format_string<Args...>`, whose converting constructor is `consteval`. It runs each `formatter::parse` at compile time against the real argument types. A dangling brace, a bad index, `{:d}` on a string, or `{:>6}` on a type whose formatter accepts no specification all fail to compile.

```cpp
#include <format>
#include <string>

std::string a = std::format("{}", 42);   // OK: literal checked at compile time
// std::format("{:d}", "text");          // ill-formed: d is not valid for strings
// std::format("{} {}", 1);              // ill-formed: too few arguments

std::string f = "{}";
// std::format(f, 1);                    // ill-formed: f is not a constant expression
```

The cost of the safety is that a format string from a file or a translation catalog does not compile. The escape hatch is `std::vformat`, which takes an ordinary `std::string_view` and a pack made with `std::make_format_args`. Errors are then reported at run time by throwing `std::format_error`.

```cpp
#include <format>
#include <string>

std::string run(const std::string& fmt, int a, int b) {
  // make_format_args takes lvalues (since C++23): rvalues do not bind
  return std::vformat(fmt, std::make_format_args(a, b));
}
// run("{} + {}", 1, 2)   returns "1 + 2"
// run("{} {} {}", 1, 2)  throws std::format_error
```

C++26 adds `std::runtime_format(str)`, which wraps a string in an object that the `format_string` constructor accepts without checking, so `std::format(std::runtime_format(f), 1)` works and still throws on bad input. The C++26 feature was not yet available in GCC 16.2 on the machine used for these examples, so treat it as the future spelling of `vformat` and prefer `vformat` today.

## Writing your own formatter

To make a type formattable, specialize `std::formatter` for it. `parse` receives the text between the colon and the closing brace and returns an iterator to the `}`; `format` writes to the context's output iterator and must be `const`.

```cpp
#include <format>

struct Rgb { unsigned char r, g, b; };

template <>
struct std::formatter<Rgb> {
  bool hex = true;
  constexpr auto parse(std::format_parse_context& ctx) {
    auto it = ctx.begin();
    if (it != ctx.end() && (*it == 'x' || *it == 'd')) hex = (*it++ == 'x');
    if (it != ctx.end() && *it != '}') throw std::format_error("bad Rgb spec");
    return it;
  }
  auto format(const Rgb& c, std::format_context& ctx) const {
    return hex ? std::format_to(ctx.out(), "#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
               : std::format_to(ctx.out(), "rgb({}, {}, {})", c.r, c.g, c.b);
  }
};
// std::format("{}", Rgb{255,0,16})   is "#ff0010"
// std::format("{:d}", Rgb{255,0,16}) is "rgb(255, 0, 16)"
```

Throwing from `parse` during compile-time checking turns into a compile error, which is how custom diagnostics are produced. A formatter that returns `ctx.begin()` without consuming anything accepts only an empty specification, so `{:>6}` on it is ill-formed. To support width and alignment for free, either inherit from `std::formatter<std::string_view>` and format into a temporary string, or pad it yourself: `std::format("{:>10}", std::format("{}", rgb))` works because the inner call produces a plain string.

Specializing `std::formatter` for your own type is allowed; the standard forbids specializing it for types you do not own, unless the specialization depends on a program-defined type.

## Ranges, tuples, and the other output functions

C++23 makes ranges, `std::pair`, and `std::tuple` formattable when their elements are. The defaults mirror the debug-friendly shape of the data: sequences print in brackets, sets in braces, maps as `{key: value}`, and tuples in parentheses with strings quoted.

```cpp
#include <format>
#include <map>
#include <print>
#include <tuple>
#include <vector>

int main() {
  std::vector<int> v{1, 2, 3};
  std::println("{}", v);                          // [1, 2, 3]
  std::println("{:n}", v);                        // 1, 2, 3  no brackets
  std::println("{::#x}", v);                      // [0x1, 0x2, 0x3]  :: is the element spec
  std::println("{}", std::make_tuple(1, "x", 2.5)); // (1, "x", 2.5)
  std::println("{}", std::map<int, int>{{1, 2}});   // {1: 2}
}
```

In a range specification, the part before the second colon applies to the range as a whole and the part after it applies to each element, which is why `{::#x}` has two colons.

The other functions differ in where the text goes:

- `std::format_to(out, fmt, args...)` writes through an output iterator and returns the end iterator. Use `std::back_inserter` for strings.
- `std::format_to_n(out, n, fmt, args...)` writes at most `n` characters and returns the end iterator and `size`, which is the length the full output would have had, not the truncated length. This is the same idea as `snprintf`'s return value.
- `std::formatted_size(fmt, args...)` returns the length without writing anything, so you can size a buffer first.

## `std::print`, Unicode, and locale

`std::print` and `std::println` (C++23, header `<print>`) format and write in one step, to `stdout` or to a `FILE*`. They are not just `std::cout << std::format(...)`. The stream is locked for the write, and if it refers to a terminal that can display Unicode only through a native API, the text is sent through that API instead of as raw bytes, so it arrives intact whatever the console code page is. This path is used when the ordinary literal encoding is UTF-8; otherwise the text is written unmodified. Invalid UTF-8 sent to such a terminal is undefined behavior, so do not print arbitrary bytes through it.

Width measurement for fill and alignment is also encoding-aware. When the literal encoding is UTF-8, the library estimates display columns, so `"{:>6}"` on `"日本"` pads with two spaces because each character takes two columns. For other encodings the method of measuring is unspecified.

Locale is opt-in. A plain `{}` is locale-independent: it ignores the global locale. Adding `L` (as in `{:L}`) uses the locale's digit grouping, decimal point, and `true`/`false` names. Overloads that take a `std::locale` as the first argument supply a specific locale for `L` to use.

## Errors, and how this compares with older tools

There are two failure channels. A malformed format string with a compile-time-checkable string is ill-formed. Everything else, such as a bad string through `vformat`, an invalid dynamic width, or a formatter that rejects a specification, throws `std::format_error`. Output functions can also throw `std::bad_alloc`, or whatever the destination iterator or stream throws.

| Tool | Type safety | Extensible | Locale by default | Cost model |
| --- | --- | --- | --- | --- |
| `printf` | None: wrong specifier is UB | No | Yes, global C locale | Varargs, parsed at run time |
| iostreams | Yes | `operator<<` | Yes, imbued locale | Virtual calls, sticky state |
| `std::format` | Yes, at compile time | `formatter` | Only with `L` | Type-erased arguments, no stream state |

The practical consequences: no sticky flags such as `std::hex` leak into later output, argument order can be changed by a translator with `{1}` and `{0}`, and the same formatter works for strings, buffers, and streams. What you lose is the ability to stream to an arbitrary `std::ostream` through `<<`. A type with `operator<<` is not automatically formattable; you need a `formatter`, and C++23 offers `std::ostream` overloads of `std::print` to send formatted text into one.

## What to remember

- A format string is parsed by `formatter<T>::parse` and written by `formatter<T>::format`; the standard spec order is fill, align, sign, `#`, `0`, width, precision, `L`, type.
- `format_string` checks the string at compile time; a non-constant string needs `vformat` with `make_format_args` (lvalues only), and C++26 adds `runtime_format`.
- Mixing automatic and manual indices is an error.
- `format_to_n` reports the untruncated size.
- `0` padding is ignored for inf and NaN, and `#` prefixes count towards the width.
- Ranges, pairs, and tuples are formattable in C++23; `{::spec}` reaches the elements.
- Locale only matters with `L`, which is valid only for arithmetic types.
- `std::print` is C++23, locks the stream while it writes, and uses Unicode-aware terminal output when the literal encoding is UTF-8.
- Runtime errors are `std::format_error`; custom formatters report bad specifications by throwing it from `parse`.

## Concept Map Outline

- **std::format and print:** A checked format string whose fields are handled by formatter<T>::parse and ::format.
  - **Format string grammar:** Literal text plus replacement fields with an optional index and spec.
    - **Standard spec order:** Fill and align, sign, #, 0, width, precision, L, then type.
    - **Argument indexing:** Use all automatic or all manual indices; mixing them is an error.
    - **Nested width and precision:** A nested {} takes width or precision from a non-negative standard integer argument.
    - **Type-dependent defaults:** Numbers align right, strings left; bool prints as text and char as a character.
  - **Checking and errors:** Errors surface at compile time when possible and as format_error otherwise.
    - **format_string is consteval:** A literal is parsed against the argument types at compile time.
    - **vformat:** Takes a runtime string and make_format_args of lvalues; throws format_error.
    - **runtime_format (C++26):** Wraps a runtime string so std::format accepts it unchecked.
    - **format_error:** Thrown by vformat, bad dynamic widths, and formatters that reject a spec.
  - **Custom formatters:** Specialize std::formatter for your own type.
    - **parse:** Consumes the spec text and returns an iterator to the closing brace.
    - **format const:** Writes to ctx.out() and must be a const member function.
    - **Reuse via delegation:** Format into a string and pad with a standard formatter to get width support.
  - **Ranges and tuples (C++23):** Containers, pairs and tuples are formattable when their elements are.
    - **Default shapes:** Sequences use brackets, sets and maps braces, tuples parentheses.
    - **Element specs:** In {::#x}, the second colon starts the spec applied to each element.
    - **n option:** {:n} removes the surrounding brackets or braces.
  - **Output functions:** Same formatters, different destinations.
    - **format_to:** Writes through an output iterator and returns the end iterator.
    - **format_to_n:** Writes at most n characters; size is the untruncated length.
    - **formatted_size:** Computes the output length without writing anything.
    - **print and println:** C++23 functions that write to stdout or a FILE*, with Unicode-aware terminal output.
  - **Unicode and locale:** Widths are in display columns, and locale is opt-in.
    - **Estimated width:** For UTF-8 literal encoding, wide East Asian characters count as two columns.
    - **L option:** Only L applies the locale's grouping, radix and bool names; plain {} ignores it.

## Standardese Quiz Questions

### Question 1 [warmup] ([format.string.std])

What does this program print?

```cpp
#include <format>
#include <print>

int main() {
  std::println("[{:5}][{:5}]", 42, "ab");
}
```

A. `[42   ][ab   ]`
B. `[   42][   ab]`
C. `[42   ][   ab]`
D. `[   42][ab   ]`

**Answer (D):** `[   42][ab   ]`

**Why:** Without an explicit alignment, arithmetic types are right-aligned and strings are left-aligned. So the integer is padded on the left and the string on the right. The tempting `printf` habit of right-aligning everything does not apply.

### Question 2 [warmup] ([format.string], [format.functions])

Is this well-formed in C++23?

```cpp
#include <format>
#include <string>

int main() {
  std::string s = std::format("{} {0}", 1);
}
```

A. Yes, it yields `"1 1"`
B. Yes, but it throws `std::format_error` at run time
C. No, ill-formed: manual and automatic indexing cannot be mixed
D. No, ill-formed only because the argument count is wrong

**Answer (C):** No, ill-formed: manual and automatic indexing cannot be mixed

**Why:** A format string must use either automatic indices (`{}`) or manual indices (`{0}`) throughout. The format string is checked by a `consteval` constructor, so the mistake is a compile error. It is not deferred to run time, which would only happen with `std::vformat`.

### Question 3 [warmup] ([format.string.std])

What does this program print?

```cpp
#include <format>
#include <print>

int main() {
  std::println("{} {:d} {}", true, true, 'a');
}
```

A. `true 1 a`
B. `1 1 97`
C. `true true a`
D. `true 1 97`

**Answer (A):** `true 1 a`

**Why:** `bool` formats as text by default and as an integer with the `d` type. A `char` formats as the character by default, unlike an integer promoted by `printf`, so it prints `a`. `true 1 97` would require `{:d}` for the char.

### Question 4 [tricky] ([format.functions])

Is this well-formed in C++23?

```cpp
#include <format>
#include <string>

int main() {
  std::string f = "{}";
  std::string s = std::format(f, 1);
}
```

A. Yes, it yields `"1"`
B. No, ill-formed: the format string must be a constant expression
C. Yes, but a bad `f` would be undefined behavior
D. Yes, but a bad `f` would throw `std::format_error`

**Answer (B):** No, ill-formed: the format string must be a constant expression

**Why:** The first parameter is `std::format_string<int>`, whose constructor is `consteval` and accepts only a string known at compile time. A non-constant `std::string` does not qualify, so this fails to compile. Use `std::vformat` for runtime strings, which then reports bad strings by throwing `std::format_error`.

### Question 5 [tricky] ([format.functions])

What is `r.size` after this call?

```cpp
#include <format>
#include <iostream>

int main() {
  char buf[16];
  auto r = std::format_to_n(buf, 5, "{}", "abcdefgh");
  std::cout << r.size << '\n';
}
```

A. `5`
B. `4`
C. `8`
D. Undefined behavior, since the output does not fit

**Answer (C):** `8`

**Why:** `format_to_n` writes at most `n` characters but reports in `size` how long the complete output would have been, like the return value of `snprintf`. That is 8 here, and only five characters were stored. It is not undefined, because truncation is the point of the function.

### Question 6 [tricky] ([format.string.std])

What does this program print?

```cpp
#include <format>
#include <iostream>
#include <limits>

int main() {
  double inf = std::numeric_limits<double>::infinity();
  std::cout << std::format("[{:06}][{:06}]", 42, inf) << '\n';
}
```

A. `[000042][000inf]`
B. `[000042][inf000]`
C. `[000042][   inf]`
D. `[   042][   inf]`

**Answer (C):** `[000042][   inf]`

**Why:** The `0` option pads with zeros for finite numbers, but the standard says it does not apply to infinity and NaN, which are padded with spaces. Zero padding would otherwise turn `inf` into text that reads like a different value. The default alignment for numbers is right, so the spaces go on the left.

### Question 7 [standardese] ([format.functions])

What does this program print?

```cpp
#include <format>
#include <iostream>
#include <string>

int main() {
  std::string f = "{} {}";
  int a = 1;
  try {
    std::string s = std::vformat(f, std::make_format_args(a));
    std::cout << s << '\n';
  } catch (const std::format_error&) {
    std::cout << "format_error\n";
  }
}
```

A. `format_error`
B. `1 ` with an empty second field
C. Nothing: the program is ill-formed
D. Nothing: undefined behavior, since an argument is missing

**Answer (A):** `format_error`

**Why:** `std::vformat` is the unchecked entry point, and the standard requires it to report a format string that does not match the arguments by throwing `std::format_error`. The same mistake with `std::format` and a literal would be a compile error instead. The call itself is well-formed because `a` is an lvalue, which `make_format_args` requires.

### Question 8 [standardese] ([format.string.std])

What does this program print?

```cpp
#include <format>
#include <iostream>

int main() {
  std::cout << std::format("{:#010x}", 255) << '\n';
}
```

A. `0x000000ff`
B. `0x00000000ff`
C. `000000x0ff`
D. `0000000xff`

**Answer (A):** `0x000000ff`

**Why:** The width of 10 counts the `0x` prefix, and the `0` option inserts the zeros after the prefix, so the result has ten characters and the digits `ff` at the end. The second option treats the width as applying only to the digits. Zeros before the prefix, as in the last two, are never produced.

# Iostreams

> An iostream is a formatting layer on top of a buffer layer, with a state word that records what went wrong. Most iostream bugs come from reading the state bits wrong, from sticky formatting, or from mixing the formatted and unformatted halves of the interface.

- **Source:** C++ Atlas (https://cppatlas.com/topics/iostreams)
- **Track:** Library utilities
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [iostate.flags] (https://eel.is/c++draft/iostate.flags), [istream.formatted] (https://eel.is/c++draft/istream.formatted), [istream.unformatted] (https://eel.is/c++draft/istream.unformatted), [ostream.formatted] (https://eel.is/c++draft/ostream.formatted), [facet.num.get.virtuals] (https://eel.is/c++draft/facet.num.get.virtuals), [iostream.objects.overview] (https://eel.is/c++draft/iostream.objects.overview), [syncstream] (https://eel.is/c++draft/syncstream), [spanstream] (https://eel.is/c++draft/spanstream)
- **cppreference links:** [std::basic_ios](https://en.cppreference.com/w/cpp/io/basic_ios), [std::basic_istream](https://en.cppreference.com/w/cpp/io/basic_istream), [std::basic_streambuf](https://en.cppreference.com/w/cpp/io/basic_streambuf), [std::ios_base::sync_with_stdio](https://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio), [std::basic_osyncstream](https://en.cppreference.com/w/cpp/io/basic_osyncstream), [std::basic_spanstream](https://en.cppreference.com/w/cpp/io/basic_spanstream), [std::setw](https://en.cppreference.com/w/cpp/io/manip/setw), [std::basic_ifstream](https://en.cppreference.com/w/cpp/io/basic_ifstream)
- **Prerequisites:** strings-and-string-view, exceptions-and-stack-unwinding

## The one idea

An iostream has two halves. The **stream** (`istream`, `ostream`) converts between values and characters and remembers the outcome. The **stream buffer** (`streambuf`) moves characters to and from a source: a file, a string, a memory span, or the C `stdout`. The stream owns a formatting state (base, width, fill, locale) and a state word with the bits `eofbit`, `failbit`, and `badbit`. Everything surprising about iostreams is a consequence of one of those three things: formatting state that persists, state bits with narrow meanings, and the buffer layer underneath.

```text
 ostream / istream / iostream      formatting, state bits, locale
          |
       basic_ios                   holds the pointer to a streambuf
          |
     streambuf                     buffering and transport
   /     |      \      \
filebuf stringbuf spanbuf syncbuf
```

> **Mental model.** The bits are not an error code. `failbit` means the last operation did not do its job, `eofbit` means the stream ran into the end while trying, and `badbit` means the buffer layer itself broke. A stream in the failed state ignores every later operation until you call `clear()`.

## The state bits and the loop idiom

`good()` is true only when no bit is set. `fail()` is true when `failbit` or `badbit` is set. `eof()` reports `eofbit` alone, and `bad()` reports `badbit` alone. A stream converts to `bool` as `!fail()`, so `if (in)` and `while (in >> x)` test whether the last extraction worked.

The common bug is testing `eof()` before reading, because `eofbit` is set only after an attempt to read past the end, and an attempt can also succeed. Reading `42` from a stream that holds exactly `"42"` sets `eofbit` because the number parser needed one more character to know it was done, yet the read succeeded.

```cpp
#include <iostream>
#include <sstream>

int main() {
  std::istringstream in("1 2 3\n");
  int x;
  while (!in.eof()) {            // bug: eof() is still false after reading 3
    in >> x;                     // fails on the trailing newline, x is untouched
    std::cout << x << ' ';       // prints 1 2 3 3
  }
}
```

The correct form puts the extraction itself in the condition.

```cpp
#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::istringstream in("1 2 3\n");
  int x;
  while (in >> x) std::cout << x << ' ';   // 1 2 3

  std::istringstream lines("a\nb\n");
  std::string line;
  while (std::getline(lines, line)) std::cout << line << ';';  // a;b;
}
```

When an extraction fails because the text is not a number, `failbit` is set and, since C++11, the target gets the value 0. If the sentry fails instead, because the stream is already in a failed state or because only whitespace remained, the target is left alone, which is why the buggy loop above repeats its last value. An out-of-range value stores the largest or smallest representable value and sets `failbit`. Extracting `"-1"` into an unsigned type is accepted and wraps, as `strtoull` would do, without setting any bit.

After a failure, call `in.clear()` to reset the state and then deal with the offending characters, usually with `in.ignore(...)`. Note also that `str("...")` on a string stream replaces the contents but does not clear the state bits, so a stream that reached the end must be cleared as well as refilled.

> **Pitfall.** `while (!in.eof())` processes the last item twice on input that ends in a newline, and loops forever on malformed input because `failbit` is set while `eofbit` never is. Test the read, not the bit.

## Formatted versus unformatted input, and mixing the two

Formatted input (`operator>>`) first skips leading whitespace, then parses a value. Unformatted input (`get`, `getline`, `read`, `ignore`, `peek`) takes characters as they come, including whitespace, and `gcount()` reports how many characters the last unformatted call extracted. Both families construct a sentry object first, which checks the stream state and, for formatted input, skips whitespace.

The classic consequence is the leftover newline.

```cpp
#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::istringstream in("5\nhello\n");
  int n;
  std::string line;
  in >> n;                  // reads 5, leaves "\nhello\n"
  std::getline(in, line);   // reads up to the newline: line is empty
  std::getline(in, line);   // line is now "hello"
}
```

Either call `in.ignore(std::numeric_limits<std::streamsize>::max(), '\n')` after the numeric read, or read whole lines first and parse them with a string stream. The latter also gives you a per-line failure state.

Since C++20, extracting into a character array uses the array's size as the limit. Before that the unbounded `operator>>(char*)` was a buffer overflow waiting for a long word, and `std::setw` was the mitigation.

## Sticky and one-shot formatting

Most manipulators change the stream's formatting state permanently: `std::hex`, `std::fixed`, `std::setprecision`, `std::setfill`, `std::left`, `std::boolalpha`. One does not: **`std::setw` applies to the next formatted output and then resets to zero.** Width also never truncates; a string longer than the width prints in full.

```cpp
#include <iomanip>
#include <iostream>

int main() {
  std::cout << std::hex << std::setw(4) << std::setfill('0') << 255 << ' ' << 255 << '\n';
  // 00ff ff   hex and fill stay, width was used up by the first 255
  std::cout << 255 << '\n';  // ff: still hex, which is why code saves and restores flags
}
```

Because the state sticks to the stream object, a function that sets `std::hex` on a stream it was given changes later output of unrelated code. Save `std::ios_base::flags()` and restore them, or format into a temporary `std::ostringstream`. This stickiness is one of the reasons the newer `std::format` is easier to reason about.

## Speed and synchronization

`std::endl` writes a newline and flushes; `'\n'` only writes a newline. Flushing on every line costs a system call for each one when the output is a file or pipe. Use `'\n'`, and flush deliberately when you need output to appear before a crash or before a prompt.

Two settings commonly slow down `cin` and `cout`. By default the standard streams are **synchronized** with C stdio, so a program may mix `printf` and `cout` and get a sensible order, at the price of typically slower, less buffered access. Calling `std::ios::sync_with_stdio(false)` before any input or output removes that, and the streams use their own buffers. After that, mixing the two APIs on the same stream is no longer safe, and the standard's guarantee that concurrent use of the standard streams from several threads is not a data race applies only while synchronized. The second setting is that `cin` is tied to `cout`, meaning `cout` is flushed before every `cin` read. `std::cin.tie(nullptr)` removes that, which is fine unless you rely on a prompt appearing first.

```cpp
#include <iostream>

int main() {
  std::ios::sync_with_stdio(false);  // before the first I/O operation
  std::cin.tie(nullptr);             // do not flush cout before each read
  int x;
  while (std::cin >> x) std::cout << x * 2 << '\n';
}
```

Even in the synchronized case, the standard only says concurrent access is free of data races; characters from different threads can still interleave. C++20's `std::osyncstream` solves that: it wraps another stream, collects output in its own buffer, and transfers it to the target as one unit when `emit()` is called or the object is destroyed. Writes from different `osyncstream` objects to the same target do not interleave.

```cpp
#include <iostream>
#include <syncstream>

void log(int id) {
  std::osyncstream out(std::cout);   // buffered privately
  out << "worker " << id << " done\n";
}                                    // destroyed here: emitted as one block
```

## String streams, span streams, files, and locale

`std::istringstream`, `std::ostringstream`, and `std::stringstream` wrap a `std::string`. `str()` returns a copy of the content, which costs an allocation. C++23's `std::ispanstream`, `std::ospanstream`, and `std::spanstream` instead use a character buffer you own, with no allocation and no copy. You read the written part back with `span()`. An `ospanstream` does not add a null terminator, and writing past the end of the buffer sets `badbit`, so size the buffer for the worst case.

File streams take an open mode, and the combination decides whether the file is created, truncated, or must already exist.

| Mode | Meaning | C equivalent |
| --- | --- | --- |
| `in` | read, must exist | `"r"` |
| `out` or `out\|trunc` | write, create or truncate | `"w"` |
| `out\|app` | append writes at the end | `"a"` |
| `in\|out` | read and write, must exist, no truncation | `"r+"` |
| `in\|out\|trunc` | read and write, create or truncate | `"w+"` |

Add `binary` to avoid newline translation on platforms that have it. An `ofstream` always adds `out` to the mode you pass, and an `ifstream` always adds `in`. A failed open does not throw by default; it sets `failbit`, so test the stream after constructing it.

Each stream holds a `std::locale` that is copied from the global locale when the stream is constructed and decides how numbers are printed and parsed: decimal point, digit grouping, `boolalpha` names. This is why changing the global locale after a stream was built does not affect that stream, and why `imbue` exists.

Finally, a stream can be told to report failures by throwing. `in.exceptions(std::ios::failbit)` makes every transition to the failed state throw `std::ios_base::failure`, which turns the end of the `while (in >> x)` loop into an exception. That is rarely what you want for input, so the usual mask is `badbit` only, or nothing. An exception thrown from inside a library formatted operation, for example by the stream buffer, is caught by the stream, recorded as `badbit`, and rethrown only if `badbit` is in the mask. A user-written `operator<<` is an ordinary function and is not wrapped this way.

## What to remember

- Streams are a formatting layer over a `streambuf`; the formatting state and the state bits live on the stream.
- `failbit` means the operation failed, `eofbit` means it hit the end, `badbit` means the buffer broke. A stream converts to `bool` as `!fail()`.
- Put the read in the loop condition: `while (in >> x)` and `while (std::getline(in, s))`. Never loop on `eof()`.
- A successful read can set `eofbit`, and a sentry failure leaves the target unchanged.
- `setw` is one-shot and never truncates; hex, fill, precision, and alignment stay until changed.
- `>>` leaves the newline behind, so `getline` after it returns an empty line.
- `'\n'` does not flush and `endl` does; `sync_with_stdio(false)` and `cin.tie(nullptr)` speed up the standard streams, at the cost of the synchronization guarantees.
- `std::osyncstream` (C++20) keeps a thread's output together; `std::spanstream` (C++23) streams over your own buffer.
- File modes decide creation and truncation; a failed open sets `failbit` and does not throw.
- `exceptions(failbit)` turns the end of a read loop into an exception.

## Concept Map Outline

- **Iostreams:** Formatting streams over stream buffers, with a state word and persistent formatting state.
  - **Layers:** Streams format and track state; stream buffers move characters.
    - **basic_ios and streambuf:** basic_ios holds a pointer to a streambuf that does the actual buffering and transport.
    - **Buffer types:** filebuf, stringbuf, spanbuf and syncbuf are the standard stream buffers.
    - **Locale per stream:** Each stream copies the global locale at construction and uses it for number formatting.
  - **State bits:** A state word records what went wrong with the last operation.
    - **failbit:** The operation did not succeed; it makes the stream convert to false.
    - **eofbit:** A read hit the end of input; it can be set even when the read succeeded.
    - **badbit:** The stream buffer lost integrity; a parse error never sets it.
    - **while (in >> x):** Put the extraction in the condition; looping on eof() repeats the last value.
    - **clear():** A failed stream ignores operations until clear(); str() does not reset the bits.
  - **Input styles:** Formatted and unformatted input behave differently around whitespace.
    - **Formatted operator>>:** Skips leading whitespace and parses a value; failure stores 0 for numbers.
    - **Unformatted functions:** get, getline, read, ignore and peek take characters as they are.
    - **Newline after >>:** operator>> leaves the newline, so a following getline returns an empty line.
  - **Output formatting:** Manipulators change formatting state, mostly permanently.
    - **Sticky manipulators:** hex, fixed, setfill, setprecision and alignment persist until changed.
    - **setw is one-shot:** Width applies to the next formatted output only and never truncates.
    - **endl versus newline:** endl writes a newline and flushes; '\n' does not flush.
  - **Performance and threads:** Standard streams are synchronized with C stdio by default.
    - **sync_with_stdio(false):** Call before any I/O; it drops C stdio mixing and the concurrent-access guarantee.
    - **cin.tie(nullptr):** Stops cout being flushed before every cin read.
    - **osyncstream:** C++20 stream that emits its buffered text to the target as one unit.
  - **Streams over memory and files:** Memory and file streams share the stream interface.
    - **String streams:** str() returns a copy and does not clear the state bits.
    - **spanstream (C++23):** Streams over a caller-owned buffer with no allocation; span() shows the written part.
    - **File open modes:** in|out requires an existing file and keeps content; out truncates; app appends.
    - **Exceptions mask:** exceptions(failbit) throws ios_base::failure, including at the end of a read loop.

## Standardese Quiz Questions

### Question 1 [warmup] ([ostream.formatted.reqmts])

What does this program print?

```cpp
#include <iomanip>
#include <iostream>

int main() {
  std::cout << std::hex << std::setw(4) << std::setfill('0') << 255 << ' ' << 255 << '\n';
}
```

A. `00ff ff`
B. `00ff 00ff`
C. `00ff 255`
D. `ff ff`

**Answer (A):** `00ff ff`

**Why:** `std::setw` applies only to the next formatted output and is then reset to zero, while `std::hex` and `std::setfill` stay in effect. The second `255` therefore prints in hex with no padding. The tempting `00ff 00ff` would need `setw(4)` repeated.

### Question 2 [warmup] ([string.io], [istream.formatted.arithmetic])

What does this program print?

```cpp
#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::istringstream in("5\nhello\n");
  int n;
  std::string line;
  in >> n;
  std::getline(in, line);
  std::cout << '[' << line << "]\n";
}
```

A. `[hello]`
B. `[5]`
C. `[]`
D. `[\n]`

**Answer (C):** `[]`

**Why:** `operator>>` for an integer stops at the newline and leaves it in the stream. `std::getline` then reads up to that newline, producing an empty string, and consumes the newline. Discard the rest of the line with `in.ignore(...)` before calling `getline`.

### Question 3 [warmup] ([facet.num.get.virtuals], [istream.formatted.arithmetic], [iostate.flags])

What does this program print?

```cpp
#include <iostream>
#include <sstream>

int main() {
  std::istringstream in("abc");
  int x = 7;
  in >> x;
  std::cout << x << ' ' << in.eof() << ' ' << in.fail() << ' ' << in.bad() << '\n';
}
```

A. `7 0 1 0`
B. `0 1 1 0`
C. `0 0 1 1`
D. `0 0 1 0`

**Answer (D):** `0 0 1 0`

**Why:** The characters do not form a number, so the conversion fails: `failbit` is set and, since C++11, the value 0 is stored. The stream was not at the end of input when the failure was detected, so `eofbit` is clear. `badbit` is reserved for loss of integrity of the stream buffer, not for a parse error, and the old value 7 is not preserved.

### Question 4 [tricky] ([istream.formatted.arithmetic], [istream.sentry], [iostate.flags])

What does this program print?

```cpp
#include <iostream>
#include <sstream>

int main() {
  std::istringstream in("1 2 3\n");
  int x;
  while (!in.eof()) {
    in >> x;
    std::cout << x << ' ';
  }
  std::cout << '\n';
}
```

A. `1 2 3 3 `
B. `1 2 3 `
C. `1 2 3 0 `
D. `1 2 3 ` and then it loops forever

**Answer (A):** `1 2 3 3 `

**Why:** After reading `3` the stream is not at EOF, because the newline is still unread, so `eof()` is false. The next `>>` skips the whitespace, reaches the end, and sets `eofbit` and `failbit` without storing anything, so `x` keeps the old value 3 and it is printed again. Testing `eof()` before reading is the bug; test the extraction itself with `while (in >> x)`.

### Question 5 [tricky] ([facet.num.get.virtuals], [iostate.flags])

What does this program print?

```cpp
#include <iostream>
#include <sstream>

int main() {
  std::istringstream in("42");
  int x = 0;
  in >> x;
  std::cout << x << ' ' << in.eof() << ' ' << in.fail() << '\n';
}
```

A. `42 0 0`
B. `42 1 0`
C. `42 1 1`
D. `0 1 1`

**Answer (B):** `42 1 0`

**Why:** To know that the number has ended, the extraction must try to read one more character, and it finds the end of input. That sets `eofbit`, but the extraction itself succeeded, so `failbit` is clear and `x` is 42. This is why `eof()` alone cannot tell you whether the last read worked.

### Question 6 [tricky] ([stringbuf.members], [istream.sentry])

What does this program print?

```cpp
#include <iostream>
#include <sstream>

int main() {
  std::istringstream in("42");
  int x = 0;
  in >> x;
  in.str("7");
  in >> x;
  std::cout << x << ' ' << in.fail() << '\n';
}
```

A. `7 0`
B. `42 1`
C. `42 0`
D. `0 1`

**Answer (B):** `42 1`

**Why:** `str()` replaces the buffer contents but does not touch the stream's state bits. The first read left `eofbit` set, so the second extraction's sentry fails, sets `failbit`, and leaves `x` at 42. Call `in.clear()` after `str(...)` to reuse the stream.

### Question 7 [standardese] ([iostate.flags])

What does this program print?

```cpp
#include <iostream>
#include <sstream>

int main() {
  std::istringstream in("1 2");
  in.exceptions(std::ios::failbit);
  int x;
  try {
    while (in >> x) std::cout << x << ',';
    std::cout << "done\n";
  } catch (const std::ios_base::failure&) {
    std::cout << "threw\n";
  }
}
```

A. `1,2,done`
B. `1,2,` then `done`, because `eofbit` is not in the mask
C. `1,2,threw`
D. `threw` immediately, before any output

**Answer (C):** `1,2,threw`

**Why:** The idiomatic loop ends because the third extraction sets `failbit`. With `failbit` in the exceptions mask, setting it throws `std::ios_base::failure` instead of returning a stream that converts to false. The `done` line is never reached. The `eofbit` is set too, but it is the `failbit` that matches the mask.

### Question 8 [standardese] ([facet.num.get.virtuals])

What does this program print?

```cpp
#include <iostream>
#include <limits>
#include <sstream>

int main() {
  std::istringstream in("-1");
  unsigned x = 0;
  in >> x;
  std::cout << (x == std::numeric_limits<unsigned>::max()) << ' ' << in.fail() << '\n';
}
```

A. `1 0`
B. `0 1`
C. `0 0`
D. `1 1`

**Answer (A):** `1 0`

**Why:** The numeric extraction converts with the rules of `strtoull`, which accepts a leading minus sign for unsigned types and negates the result modulo the type's range. So `-1` becomes the maximum value and no failure is reported. The tempting `0 1` assumes the library rejects a negative number for an unsigned target; it does not.

# std::filesystem

> A path is a value that names a location, not a handle to a file, and most of its member functions are pure text manipulation. The rest of the library asks the operating system questions whose answers can change at any moment, which is why every operation comes in a throwing and a non-throwing form and why check-then-act code is wrong.

- **Source:** C++ Atlas (https://cppatlas.com/topics/filesystem)
- **Track:** Library utilities
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [fs.class.path] (https://eel.is/c++draft/fs.class.path), [fs.path.generic] (https://eel.is/c++draft/fs.path.generic), [fs.path.append] (https://eel.is/c++draft/fs.path.append), [fs.path.compare] (https://eel.is/c++draft/fs.path.compare), [fs.err.report] (https://eel.is/c++draft/fs.err.report), [fs.race.behavior] (https://eel.is/c++draft/fs.race.behavior), [fs.enum.copy.opts] (https://eel.is/c++draft/fs.enum.copy.opts), [fs.op.canonical] (https://eel.is/c++draft/fs.op.canonical)
- **cppreference links:** [std::filesystem::path](https://en.cppreference.com/w/cpp/filesystem/path), [std::filesystem::path::lexically_normal](https://en.cppreference.com/w/cpp/filesystem/path/lexically_normal), [std::filesystem::canonical](https://en.cppreference.com/w/cpp/filesystem/canonical), [std::filesystem::directory_iterator](https://en.cppreference.com/w/cpp/filesystem/directory_iterator), [std::filesystem::recursive_directory_iterator](https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator), [std::filesystem::copy_options](https://en.cppreference.com/w/cpp/filesystem/copy_options), [std::filesystem::file_status](https://en.cppreference.com/w/cpp/filesystem/file_status), [std::filesystem::space](https://en.cppreference.com/w/cpp/filesystem/space), [std::filesystem::file_time_type](https://en.cppreference.com/w/cpp/filesystem/file_time_type), [std::filesystem::path::u8path](https://en.cppreference.com/w/cpp/filesystem/path/u8path)
- **Prerequisites:** strings-and-string-view, optional-expected-and-error-codes, chrono

## The one idea

The library has two layers that look alike and behave nothing alike. A `std::filesystem::path` is a value type holding a string and rules for splitting it into pieces. Most of its members, `filename`, `extension`, `parent_path`, `lexically_normal`, never touch the disk. Everything else, `exists`, `canonical`, `directory_iterator`, `copy`, is a request to an operating system that shares the disk with every other process. Those answers describe the moment of the call and nothing longer.

> **Mental model.** A path is text. A filesystem function is a question to the world. Never expect a text operation to know what is on disk, and never expect an answer from the disk to still be true on the next line.

## Path as text

On POSIX a path stores `char`, and on Windows `wchar_t`. `native()` returns that storage; `string()` converts it to a narrow string in the platform's encoding; `generic_string()` converts it and also uses `/` as the separator. The **generic format** is the portable spelling with forward slashes, and the **native format** is whatever the platform prefers. On POSIX they are the same.

Decomposition follows lexical rules that are worth knowing exactly:

```cpp
#include <filesystem>
#include <iostream>

int main() {
  using std::filesystem::path;
  path p = "/tmp/archive.tar.gz";
  std::cout << p.stem() << ' ' << p.extension() << '\n';   // "archive.tar" ".gz"
  std::cout << path(".bashrc").extension() << '\n';         // "" a leading dot is not an extension
  std::cout << path("a/b/").filename() << '\n';             // "" trailing separator gives empty filename
  std::cout << path("a/b/").parent_path() << '\n';          // "a/b"
  for (auto& part : path("a/b/")) std::cout << '<' << part << '>';  // <a><b><>
}
```

Joining paths has one rule that causes real bugs. `operator/` is `append`, and `append` **replaces** the left side when the right side is absolute, because an absolute path already names a complete location.

```cpp
#include <filesystem>
using std::filesystem::path;

void demo() {
  path a = path("/usr/lib") / "/opt";   // "/opt", the left side is discarded
  path b = path("/usr/lib") / "opt";    // "/usr/lib/opt"
  path c = path("a") / "";              // "a/", an empty right side adds a separator
  path d = "a";
  d += "b";                             // += is plain concatenation: "ab", no separator
}
```

This means `base / user_supplied` can escape `base` when the supplied part starts with `/`, or with `..`. Validate it as text before joining, then verify the result against the real filesystem.

Equality compares element by element. `path("a//b") == path("a/b")` is true because repeated separators vanish, but `path("a/b/")` differs from `path("a/b")` because of the trailing empty element, and `a/./b` differs from `a/b` because `.` is an element. Comparison never normalizes.

## Lexical operations versus filesystem operations

`lexically_normal` removes `.` elements and cancels `name/..` pairs, all as text. `lexically_relative` and `lexically_proximate` compute a path from one to another, also as text. They are fast, never fail, and are right whenever no symlinks are involved. If the result would be empty, `lexically_normal` returns `.`.

The filesystem counterparts ask the operating system. `canonical` makes an absolute path with every symlink resolved, and fails if the path does not exist. `weakly_canonical` resolves as much of the prefix as exists and normalizes the rest lexically, so it works on a path you are about to create. `absolute` only prepends the current directory and does no resolution at all. `equivalent` asks whether two paths reach the same object.

```text
root/
  real/
    sub/
  link -> real/sub

path "root/link/.."
  lexically_normal   -> "root"        link and .. cancel, as text
  canonical          -> ".../real"    the link was followed first, then .. applied
```

The difference matters for security checks. A containment test written with `lexically_normal` and `starts_with` can be defeated by a symlink inside the tree. Resolve with `weakly_canonical` before comparing, and remember that even this is a snapshot.

> **Pitfall.** `lexically_normal` assumes `link/..` names the directory that contains `link`. If `link` is a symlink, the operating system instead gives the parent of the link's target, so the textual answer is a different directory.

## Two error-reporting channels

Nearly every operation has two overloads. The plain one throws `std::filesystem::filesystem_error`, which carries the error code and the paths involved. The overload taking a `std::error_code&` reports failure through that argument and does not throw `filesystem_error`, although functions that allocate can still throw `std::bad_alloc`. When the call fails, the non-throwing form returns a documented sentinel: `file_size` returns `static_cast<std::uintmax_t>(-1)`, and queries such as `exists` return false.

```cpp
#include <filesystem>
#include <iostream>
#include <system_error>

namespace fs = std::filesystem;

void demo(const fs::path& p) {
  try {
    auto n = fs::file_size(p);                // throws filesystem_error if p is missing
    std::cout << n << '\n';
  } catch (const fs::filesystem_error& e) {
    std::cout << e.what() << ' ' << e.path1() << '\n';
  }
  std::error_code ec;
  auto n = fs::file_size(p, ec);              // no throw: n is uintmax_t(-1), ec is set
  if (ec) std::cout << ec.message() << '\n';
}
```

Use the throwing form when failure is exceptional, and the `error_code` form in loops where failure is an expected case. Plain `exists(p)` returns false for a path that is not there without throwing, but throws if the error is something else, such as a permission failure on a parent directory.

## Symlinks, status, and iteration

`status` follows symlinks and `symlink_status` does not. Free functions such as `exists`, `is_directory`, and `is_regular_file` are built on `status`, so a dangling symlink is reported as non-existent, while `is_symlink` is built on `symlink_status` and still sees it. A `file_status` bundles a `file_type` and permission bits.

```cpp
#include <filesystem>
namespace fs = std::filesystem;

// dir/link -> dir/missing  (the target does not exist)
// fs::exists(dir / "link")       is false: status follows the link
// fs::is_symlink(dir / "link")   is true:  symlink_status does not
```

`directory_iterator` visits the entries of one directory, in an unspecified order, and never yields `.` or `..`. `recursive_directory_iterator` descends into subdirectories, but by default it **skips directory symlinks**; the option `follow_directory_symlink` turns following on, and with it comes the risk of cycles. Dereferencing gives a `directory_entry`, which caches attributes, so `e.is_directory()` may avoid a system call but may also be stale. Call `refresh()` or use the free function when freshness matters. If a directory cannot be read, the default is an error; `skip_permission_denied` skips it instead.

## Races, copying, space, and time

The standard states that the behavior is undefined if a call to a filesystem function introduces a **file system race**: threads, processes, or machines interleaving access and modification of the same object in the file system. The consequence for programs is clear. `if (!exists(p)) create_directory(p);` has a gap between the test and the act, called TOCTOU (time of check to time of use), in which another process can act. Do the operation and handle the failure instead: `create_directory` returns false rather than failing when the directory already exists, and an error-code overload gives the reason when something else is wrong.

`copy_file` fails by default when the destination exists. `copy_options` decides what happens instead:

| Option | Effect |
| --- | --- |
| `skip_existing` | leave the existing destination alone and report no copy |
| `overwrite_existing` | replace it |
| `update_existing` | replace it only if the source is newer |
| `recursive` | for `copy`, descend into directories |
| `copy_symlinks`, `skip_symlinks` | copy links as links, or skip them |

`fs::space(p)` returns three numbers: `capacity`, `free`, and `available`. `available` is what an unprivileged process may use and can be smaller than `free`. The values are a snapshot, so reserving space by looking at them is another race.

Timestamps use `std::filesystem::file_time_type`, a `time_point` of an implementation-specific clock before C++20 and of `std::chrono::file_clock` since. It is **not** `system_clock`, and its epoch may differ. Convert with `std::chrono::clock_cast<std::chrono::system_clock>(t)` in C++20 and later, and do not subtract it from a `system_clock` time directly.

## Encoding and C++20 char8_t

A `u8` literal has type `char8_t` in C++20. `path::u8string()` therefore returns `std::u8string` in C++20 and `std::string` in C++17, and code like `std::string s = p.u8string();` stops compiling when the language version moves. Convert deliberately, by copying the bytes or by reinterpreting, and decide at your own boundary which encoding your narrow strings use. The factory `u8path(str)` that existed to say "this string is UTF-8" is deprecated in C++20, since a path can be constructed from a `u8string` or `char8_t` range directly. On POSIX, a `path` built from a `std::string` keeps the bytes unchanged, whatever they mean, while on Windows narrow strings are converted using the system code page unless you go through the wide or UTF-8 forms.

## What to remember

- A `path` is text; only the free functions and iterators consult the disk.
- `operator/` and `append` replace the left side when the right side is absolute; `+=` concatenates without a separator.
- `lexically_normal` is purely textual, returns `.` for an empty result, and is wrong across symlinks; `canonical` requires existence, and `weakly_canonical` does not.
- Path comparison is by elements: `a//b == a/b`, but a trailing slash or a `.` element makes paths differ.
- Every operation has a throwing overload and an `error_code` overload that does not throw `filesystem_error`.
- `status` follows symlinks and `symlink_status` does not; `exists` on a dangling symlink is false.
- Directory iteration order is unspecified, `.` and `..` are skipped, and recursive iteration does not follow directory symlinks by default.
- Interleaved access by others is a file system race, which the standard makes undefined; do the operation and handle its failure instead of testing first.
- `copy_file` fails on an existing target unless `copy_options` says otherwise, and `space` results are only a snapshot.
- `file_time_type` uses its own clock; use `clock_cast` to reach `system_clock`.
- `u8string()` returns `std::u8string` since C++20, and `u8path` is deprecated.

## Concept Map Outline

- **std::filesystem:** Path is text; the other functions ask an OS that others may change at any time.
  - **Path as a value:** A path holds a string and splits it by lexical rules.
    - **Generic vs native:** Generic uses forward slashes; native is the platform's own form, and on POSIX they match.
    - **Decomposition:** stem and extension split at the last dot; a leading dot is not an extension.
    - **Trailing separator:** a/b/ iterates as a, b and an empty element, and its filename() is empty.
    - **Comparison:** Elementwise: a//b equals a/b, but a trailing slash or a dot element differs.
  - **Joining paths:** operator/ is append, not string concatenation.
    - **Absolute right side:** An absolute right-hand path replaces the left side entirely.
    - **Empty right side:** path("a") / "" gives a/ with a trailing separator.
    - **operator+=:** Plain concatenation with no separator inserted.
  - **Lexical vs real:** Text functions never touch the disk; resolving functions do.
    - **lexically_normal:** Cancels dot and name/.. as text and yields . when the result is empty.
    - **canonical:** Resolves symlinks and requires the path to exist.
    - **weakly_canonical:** Resolves the existing prefix and normalizes the rest textually.
    - **link/.. trap:** The OS follows link first, so link/.. differs from the lexical result.
  - **Errors and status:** Two overload families and symlink-aware queries.
    - **Throwing overload:** Throws filesystem_error carrying the code and the paths.
    - **error_code overload:** Reports through the argument, with a sentinel return such as uintmax_t(-1).
    - **status vs symlink_status:** status follows links; exists is false for a dangling symlink.
  - **Iteration and operations:** Directory walks and bulk operations depend on options.
    - **directory_iterator:** Unspecified order; skips . and ..
    - **recursive iterator:** Does not follow directory symlinks unless follow_directory_symlink is set.
    - **copy_options:** copy_file fails on an existing target unless skip, overwrite or update is chosen.
    - **space:** Reports capacity, free and available; available can be less than free.
  - **Races, time, encoding:** The disk is shared and the types have platform-specific parts.
    - **File system races:** The standard makes calls that introduce a race undefined; avoid check-then-act.
    - **file_time_type:** Uses file_clock since C++20; convert with clock_cast to system_clock.
    - **u8string in C++20:** Returns std::u8string, which does not convert to std::string; u8path is deprecated.

## Standardese Quiz Questions

### Question 1 [warmup] ([fs.path.append])

On a POSIX system, what does this program print?

```cpp
#include <filesystem>
#include <iostream>

int main() {
  std::filesystem::path p = "/usr/lib";
  std::cout << (p / "/opt").string() << '\n';
}
```

A. `/usr/lib/opt`
B. `/usr/lib//opt`
C. `/usr/lib`
D. `/opt`

**Answer (D):** `/opt`

**Why:** `operator/` follows the rules of `append`: if the right-hand operand is absolute, it replaces the left-hand path instead of being joined to it. The result is `/opt`. Plain string concatenation would give the first option, which is what `+=` on a path does for relative text.

### Question 2 [warmup] ([fs.path.decompose])

What does this program print?

```cpp
#include <filesystem>
#include <iostream>

int main() {
  std::filesystem::path p = "/tmp/archive.tar.gz";
  std::cout << p.stem().string() << ' ' << p.extension().string() << '\n';
}
```

A. `archive .tar.gz`
B. `archive.tar .gz`
C. `archive.tar.gz .gz`
D. `archive .gz`

**Answer (B):** `archive.tar .gz`

**Why:** The extension is the part of the filename from the last dot, so it is `.gz`, and the stem is everything before that, which is `archive.tar`. Peeling several extensions requires calling `stem()` repeatedly.

### Question 3 [warmup] ([fs.op.exists], [fs.op.is.symlink])

On a POSIX system, what does this program print?

```cpp
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
  fs::path dir = fs::temp_directory_path() / "atlas_dangling_demo";
  fs::remove_all(dir);
  fs::create_directory(dir);
  fs::create_symlink(dir / "missing", dir / "link");
  std::cout << fs::exists(dir / "link") << ' ' << fs::is_symlink(dir / "link") << '\n';
  fs::remove_all(dir);
}
```

A. `0 1`
B. `1 1`
C. `0 0`
D. `1 0`

**Answer (A):** `0 1`

**Why:** `exists` and `is_regular_file` use `status`, which follows symlinks, so a symlink whose target is missing is reported as not existing. `is_symlink` uses `symlink_status`, which looks at the link itself, and finds one. To ask about the link, use the `symlink_status` family.

### Question 4 [tricky] ([fs.path.generic])

What does this program print?

```cpp
#include <filesystem>
#include <iostream>

int main() {
  std::filesystem::path p = "a/b/../..";
  std::cout << '[' << p.lexically_normal().string() << "]\n";
}
```

A. `[]`
B. `[.]`
C. `[a/b/../..]`
D. `[..]`

**Answer (B):** `[.]`

**Why:** Normalization removes `b/..` and then `a/..`, leaving nothing. The standard says that if the result would be empty it is a single dot. An empty path means no path at all, so the dot is the way to name the current directory.

### Question 5 [tricky] ([fs.path.generic], [fs.op.equivalent])

On a POSIX system, what does this program print?

```cpp
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
  fs::path root = fs::temp_directory_path() / "atlas_dotdot_demo";
  fs::remove_all(root);
  fs::create_directories(root / "real" / "sub");
  fs::create_directory_symlink(root / "real" / "sub", root / "link");

  fs::path p = root / "link" / "..";
  std::cout << fs::equivalent(p, root / "real") << ' '
            << fs::equivalent(p.lexically_normal(), root / "real") << '\n';
  fs::remove_all(root);
}
```

A. `0 1`
B. `1 1`
C. `0 0`
D. `1 0`

**Answer (D):** `1 0`

**Why:** The operating system resolves `link/..` by following the link first, so it names the parent of `real/sub`, which is `real`. Lexical normalization knows nothing about links and cancels `link/..`, leaving `root`, which is a different directory. That is why `lexically_normal` is unsafe on paths that may contain symlinks, and why `canonical` exists.

### Question 6 [tricky] ([fs.path.compare], [fs.path.itr])

What does this program print?

```cpp
#include <filesystem>
#include <iostream>

int main() {
  using std::filesystem::path;
  std::cout << (path("a//b") == path("a/b")) << ' '
            << (path("a/b/") == path("a/b")) << ' '
            << (path("a/./b") == path("a/b")) << '\n';
}
```

A. `1 1 1`
B. `0 0 0`
C. `1 0 0`
D. `1 1 0`

**Answer (C):** `1 0 0`

**Why:** Path comparison goes element by element, and repeated separators do not create extra elements, so `a//b` equals `a/b`. A trailing separator does produce a final empty element, and `.` is an element, so the other two comparisons are false. Comparison never normalizes.

### Question 7 [standardese] ([fs.path.native.obs], [fs.path.type.cvt])

Is this well-formed in C++20?

```cpp
#include <filesystem>
#include <string>

int main() {
  std::filesystem::path p(u8"caf\u00e9");
  std::string s = p.u8string();
  (void)s;
}
```

A. Yes: `u8string()` returns a `std::string` holding UTF-8
B. Yes, but only if the file name is ASCII
C. No: `u8string()` returns `std::u8string`, which does not convert to `std::string`
D. No: a `path` cannot be constructed from a `u8` literal

**Answer (C):** No: `u8string()` returns `std::u8string`, which does not convert to `std::string`

**Why:** C++20 changed `path::u8string()` to return `std::u8string`, because UTF-8 text now has its own character type. A `std::u8string` cannot be converted to `std::string`. In C++17, where `u8` literals are `char`, the same code compiles. Construction from a `u8` literal is fine in both versions.

### Question 8 [standardese] ([fs.err.report], [fs.op.file.size])

What does this program print?

```cpp
#include <cstdint>
#include <filesystem>
#include <iostream>
#include <system_error>

int main() {
  std::error_code ec;
  std::uintmax_t n = std::filesystem::file_size("/no/such/file/anywhere", ec);
  std::cout << static_cast<bool>(ec) << ' '
            << (n == static_cast<std::uintmax_t>(-1)) << '\n';
}
```

A. `1 1`
B. `1 0`
C. `0 0`
D. Nothing: it throws `std::filesystem::filesystem_error`

**Answer (A):** `1 1`

**Why:** The overload taking an `error_code&` reports failure through the argument and never throws a `filesystem_error`; the standard specifies that `file_size` returns `static_cast<uintmax_t>(-1)` on error. Without the `ec` argument, the same call throws. The `ec` argument is set to the system's error code.

# Random numbers

> The random library splits randomness into engines that produce raw bits, distributions that shape them into values, and a seed that decides where an engine starts. Each of those parts has traps, from modulo bias and weak seeding to distributions whose output differs between standard libraries.

- **Source:** C++ Atlas (https://cppatlas.com/topics/random-numbers)
- **Track:** Library utilities
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [rand.eng.mers] (https://eel.is/c++draft/rand.eng.mers), [rand.predef] (https://eel.is/c++draft/rand.predef), [rand.dist.uni.int] (https://eel.is/c++draft/rand.dist.uni.int), [rand.dist.uni.real] (https://eel.is/c++draft/rand.dist.uni.real), [rand.util.canonical] (https://eel.is/c++draft/rand.util.canonical), [alg.random.shuffle] (https://eel.is/c++draft/alg.random.shuffle), [alg.random.sample] (https://eel.is/c++draft/alg.random.sample), [c.math.rand] (https://eel.is/c++draft/c.math.rand)
- **cppreference links:** [Pseudo-random number generation](https://en.cppreference.com/w/cpp/numeric/random), [std::random_device](https://en.cppreference.com/w/cpp/numeric/random/random_device), [std::mersenne_twister_engine](https://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine), [std::uniform_int_distribution](https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution), [std::uniform_real_distribution](https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution), [std::seed_seq](https://en.cppreference.com/w/cpp/numeric/random/seed_seq), [std::generate_canonical](https://en.cppreference.com/w/cpp/numeric/random/generate_canonical), [std::philox_engine](https://en.cppreference.com/w/cpp/numeric/random/philox_engine), [std::rand](https://en.cppreference.com/w/cpp/numeric/random/rand)
- **Prerequisites:** algorithms, concepts-and-constraints, threads-and-jthread

## The one idea

A random number in C++ comes from three separate objects. A **uniform random bit generator** is a source of unsigned integers spread over a fixed range: an engine such as `std::mt19937`, an adaptor over one, or `std::random_device`. A **distribution** such as `uniform_int_distribution` takes bits from a generator and turns them into the values you actually want. A **seed** decides where a pseudo-random engine starts. Everything you can get wrong is about one of these three: the generator is weaker than you assumed, the distribution is not what you think, or the seed has far fewer possibilities than the engine has states.

```cpp
#include <iostream>
#include <random>

int main() {
  std::random_device rd;                         // seed source: slow, called once
  std::mt19937 gen(rd());                        // engine: deterministic given the seed
  std::uniform_int_distribution<int> die(1, 6);  // distribution: closed interval [1, 6]
  for (int i = 0; i < 5; ++i) std::cout << die(gen) << ' ';
}
```

> **Mental model.** An engine is a deterministic state machine. Same seed, same sequence, on every conforming implementation. Randomness in a program comes only from the seed, and the quality of a program's randomness cannot exceed the quality of its seed.

## Why `rand() % n` is wrong

`std::rand` hands out values in `[0, RAND_MAX]`, where `RAND_MAX` is at least 32767, from hidden global state that you seed with `srand`. Its algorithm and quality are left to the implementation. The remainder trick has a second flaw. Unless `RAND_MAX + 1` is a multiple of `n`, some residues occur more often than others. With a range of 32768 and `n = 6`, the numbers are `5461 * 6 + 2`, so results 0 and 1 are slightly more likely than the others. The effect is tiny for small `n` and severe when `n` is a large fraction of the range. Taking low bits of a weak generator can also be worse than the generator itself.

`std::uniform_int_distribution` avoids the bias; implementations typically do this by consuming as many engine outputs as they need and rejecting values that fall in the uneven tail. It also works with engines whose range is not a power of two. Prefer it to any hand-written reduction.

## Engines and adaptors

The standard supplies three families of engines. `linear_congruential_engine` is tiny and fast and has weak statistical properties. `mersenne_twister_engine`, with the aliases `mt19937` and `mt19937_64`, has a large state and long period. `subtract_with_carry_engine` is the third. **Adaptors** wrap an engine and change its output: `discard_block_engine` throws away part of each block, `independent_bits_engine` repacks bits into a chosen width, and `shuffle_order_engine` (as in `knuth_b`) permutes the output order. `std::default_random_engine` is a typedef whose engine is implementation-defined, so it gives you no portability promise.

The predefined engines have a strong guarantee, because their algorithms and default seeds are specified. The standard states that the 10000th invocation of a default-constructed `mt19937` returns 4123659995, and the other predefined engines have the same kind of check value.

```cpp
#include <iostream>
#include <random>

int main() {
  std::mt19937 g;                        // default seed 5489
  for (int i = 1; i < 10000; ++i) g();
  std::cout << g() << '\n';              // 4123659995 on every conforming implementation
}
```

## Seeding

`std::random_device` is meant to produce non-deterministic numbers from the operating system or hardware. The standard permits an implementation to fall back on a pseudo-random engine if no such source exists, in which case every object may produce the same sequence, so on exotic platforms it can fail to be random at all. Its `entropy()` member is an estimate and not a reliable test of this. It is also slow compared with an engine, and on some systems it degrades when called often. Use it to seed an engine, not as the engine.

The usual one-liner `std::mt19937 gen(std::random_device{}())` seeds with a single 32-bit value. The mt19937 state has 19937 bits, but a single-value seed reduces to 32 bits, so there are at most 2^32 reachable sequences, and the engine is not seeded from anything close to its capacity. Seeding with `1ULL << 32` gives the same engine as seeding with 0. To spread more entropy into the state, give the engine a **seed sequence**:

```cpp
#include <array>
#include <cstdint>
#include <random>

std::mt19937 make_engine() {
  std::random_device rd;
  std::array<std::uint32_t, 8> seed_data;
  for (auto& x : seed_data) x = rd();
  std::seed_seq seq(seed_data.begin(), seed_data.end());
  return std::mt19937(seq);              // state filled from 256 bits of seed data
}
```

`seed_seq` scrambles whatever it is given into as many 32-bit words as the engine asks for. It cannot create entropy that was not there, so eight words from a bad `random_device` are still a bad seed.

## Distributions are not portable

Engines are specified exactly; distributions are not. The standard says what distribution a class produces, such as uniform over `[a, b]`, but not which algorithm computes it or how many engine outputs it uses. As a result, the same engine and seed can yield different dice rolls on libstdc++ and libc++, and `std::shuffle` is just as unspecified. The raw engine output is the same everywhere.

If you need reproducible results across platforms, for tests with golden files or for networked simulations, take the engine's raw output and write the mapping yourself, or ship your own distribution implementation. Within one build of one library the sequence is reproducible, but an upgrade of the library may change it.

Distributions can also hold **state**. A normal distribution, for example, commonly produces values in pairs and keeps the spare one. Calling `reset()` discards such cached state, so the next call draws fresh engine output. Copying a distribution copies this state with it. If you want one fixed stream per task, do not share distribution objects between tasks.

## Ranges and types

`uniform_int_distribution<T>(a, b)` is a closed interval: both `a` and `b` can occur. Passing `a > b` violates a precondition and is undefined behavior; nothing swaps the bounds. The type `T` must be one of `short`, `int`, `long`, `long long` or their unsigned versions. The effect of `char`, `signed char`, `unsigned char`, `char8_t`, `wchar_t` or `bool` is undefined. libstdc++ accepts `char`, libc++ rejects it with a `static_assert`, and neither tells you what the standard does. Generate an `int` and cast.

`uniform_real_distribution<T>(a, b)` is **half-open**, `[a, b)`. The mathematics says `b` never appears, but floating-point rounding is a known trouble: the function `generate_canonical`, which underlies it, was specified in a way that let several implementations occasionally return exactly `1.0` for `float`, a defect tracked as LWG 2524. Code that divides by `1 - x` or uses `x` as an array index scaled by the size must not rely on the upper bound being excluded without a guard. A closed real interval is hard to build: using `nextafter(b)` as the upper limit does not always work because of rounding.

`std::generate_canonical<double, 53>(gen)` yields a real in `[0, 1)` using the stated number of bits. It is the building block for most real-valued distributions, and the place the rounding problem comes from.

## Shuffling, sampling, and threads

`std::shuffle(first, last, gen)` permutes a range using a generator. `std::random_shuffle` was deprecated in C++14 and removed in C++17 because it relied on `rand`. `std::sample(first, last, out, n, gen)` (C++17) selects `n` elements without replacement. The result preserves the order of the input only if the input iterators are forward iterators, and which elements are chosen is unspecified in the sense described for distributions: different libraries select differently.

Engines and distributions are ordinary objects with no internal locking. Calling `operator()` on the same object from two threads at once is a data race. Give each thread its own engine, for example a `thread_local` one, and seed each from a seed sequence built from distinct values. Sharing one engine behind a mutex is correct but serializes the threads.

## C++26 additions

C++26 adds `std::philox_engine` with the aliases `philox4x32` and `philox4x64`. This is a **counter-based** engine: its state is small and a position in the sequence can be addressed directly, which suits parallel work where each thread or work item takes its own stream. The aliases have a specified check value for the 10000th output, and GCC 16.2 produces 1955073260 for `philox4x32`, matching it. C++26 also adds `std::ranges::generate_random`, which fills a range with random numbers drawn from a generator, optionally through a distribution. GCC 16.2 does not provide it, so it has not been run for this topic.

## What to remember

- Engine, distribution, and seed are separate; randomness comes only from the seed.
- `rand() % n` is biased unless `n` divides `RAND_MAX + 1`; use `uniform_int_distribution`.
- Predefined engines are fully specified: `mt19937` default-constructed yields 4123659995 on its 10000th call, on every conforming implementation.
- Distributions and `shuffle` are not specified at the algorithm level, so they differ between libraries.
- `uniform_int_distribution` is `[a, b]` and requires `a <= b`; `uniform_real_distribution` is `[a, b)`, with a rounding caveat in `generate_canonical`.
- Only the listed standard integer types work with the integer distributions; `char` and `bool` have undefined effects.
- `random_device` may be deterministic on some platforms and is slow; use it to seed.
- One 32-bit seed reaches at most 2^32 states of `mt19937`; `seed_seq` helps spread seed data but cannot create entropy.
- Do not share an engine or distribution between threads without synchronization.
- `reset()` clears a distribution's cached state; `sample` is stable only with forward iterators.
- C++26 adds `philox_engine` and `ranges::generate_random`.

## Concept Map Outline

- **Random numbers:** Engines produce bits, distributions shape them, and the seed decides the start.
  - **Three parts:** Generator, distribution and seed are separate objects with separate failure modes.
    - **Engines:** Deterministic state machines: same seed gives the same sequence on every implementation.
    - **Adaptors:** discard_block, independent_bits and shuffle_order engines wrap another engine.
    - **Distributions:** Turn engine output into values; the algorithm is not specified, so results vary by library.
    - **Predefined check value:** The 10000th call of a default mt19937 returns 4123659995.
  - **Why not rand():** std::rand has hidden global state and implementation-defined quality.
    - **Modulo bias:** rand() % n favors some residues unless n divides RAND_MAX + 1.
    - **Small RAND_MAX:** RAND_MAX is only guaranteed to be at least 32767.
    - **random_shuffle removed:** It used rand and was removed in C++17; use shuffle with an engine.
  - **Seeding:** A program's randomness cannot exceed its seed's.
    - **random_device:** Meant to be non-deterministic, but may be a fixed pseudo-random engine on some platforms.
    - **Single 32-bit seed:** Reaches at most 2^32 of mt19937's states; 1<<32 and 0 give the same engine.
    - **seed_seq:** Spreads seed words over the engine state but cannot add entropy.
  - **Distribution rules:** Interval conventions and permitted types differ per distribution.
    - **Integer is closed:** uniform_int_distribution gives [a, b] and needs a <= b, else undefined behavior.
    - **Real is half-open:** uniform_real_distribution gives [a, b), but rounding has returned b in some libraries.
    - **Allowed int types:** Only short, int, long, long long and unsigned forms; char and bool are undefined.
    - **State and reset:** Distributions may cache values, as normal does; reset discards the cache.
  - **Algorithms and threads:** Shuffle and sample take a generator, and generators are not thread-safe.
    - **shuffle:** Permutes a range with a generator; results differ between libraries.
    - **sample:** C++17 selection without replacement; stable only for forward iterators.
    - **Thread safety:** Concurrent calls on one engine or distribution race; use one engine per thread.
  - **C++26:** Counter-based generation for parallel work.
    - **philox_engine:** Counter-based engine with philox4x32 and philox4x64 aliases.
    - **generate_random:** Ranges algorithm that fills a range from a generator; not in GCC 16.2.

## Standardese Quiz Questions

### Question 1 [warmup] ([rand.dist.uni.int])

What does this program print?

```cpp
#include <iostream>
#include <random>

int main() {
  std::uniform_int_distribution<int> d(1, 6);
  std::cout << d.min() << ' ' << d.max() << '\n';
}
```

A. `1 5`
B. `0 6`
C. `1 7`
D. `1 6`

**Answer (D):** `1 6`

**Why:** `uniform_int_distribution` produces values on the closed interval `[a, b]`, so both bounds can occur and `max()` is 6. The half-open convention belongs to `uniform_real_distribution`, and carrying it over to integers is the usual off-by-one.

### Question 2 [warmup] ([rand.eng.mers])

What does this program print?

```cpp
#include <iostream>
#include <random>

int roll() {
  std::mt19937 gen(42);
  std::uniform_int_distribution<int> d(1, 6);
  return d(gen);
}

int main() {
  std::cout << (roll() == roll()) << '\n';
}
```

A. `1`
B. `0`
C. Unspecified: it depends on the platform's clock
D. Undefined behavior

**Answer (A):** `1`

**Why:** Each call builds a new engine from the same seed and a new distribution in the same initial state, so both calls compute exactly the same value. An engine is a deterministic function of its state. Creating the engine inside a frequently called function is a common cause of a random generator that always returns the same number.

### Question 3 [warmup] ([c.math.rand])

Assume `RAND_MAX` is 32767 and `rand()` returns each value in `[0, 32767]` exactly once per 32768 draws. Which results of `rand() % 6` come up more often than the others?

A. None: each result is equally likely
B. `0` and `1`
C. `4` and `5`
D. `0` only

**Answer (B):** `0` and `1`

**Why:** There are 32768 inputs and 6 results, and 32768 = 6 * 5461 + 2. The inputs 0 to 32765 split evenly, and the two left-over inputs, 32766 and 32767, map to results 0 and 1. Those two results each occur 5462 times against 5461 for the rest. The bias is small here but grows as the modulus approaches the range, which is why `uniform_int_distribution` rejects or rescales instead of taking a remainder.

### Question 4 [tricky] ([rand.eng.mers], [rand.dist.uni.int], [alg.random.shuffle])

The program below runs on two conforming implementations, each with a different standard library. Which of the lines are guaranteed to print the same values on both?

```cpp
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>

int main() {
  std::mt19937 e1(42);
  std::cout << e1() << '\n';                       // line 1

  std::mt19937 e2(42);
  std::uniform_int_distribution<int> d(1, 6);
  std::cout << d(e2) << '\n';                      // line 2

  std::mt19937 e3(42);
  std::vector<int> v(10);
  std::iota(v.begin(), v.end(), 0);
  std::shuffle(v.begin(), v.end(), e3);
  std::cout << v[0] << '\n';                       // line 3
}
```

A. Only line 1
B. Lines 1 and 2
C. Lines 1 and 3
D. All three lines

**Answer (A):** Only line 1

**Why:** The standard defines the algorithm of `mt19937`, including seeding from a single value, so its raw output is the same everywhere. It does not define how a distribution turns engine output into a value or how `shuffle` consumes it, so lines 2 and 3 can differ between libraries. They do differ between libstdc++ and libc++ for this seed.

### Question 5 [tricky] ([rand.eng.mers])

What does this program print?

```cpp
#include <iostream>
#include <random>

int main() {
  std::mt19937 a(1ULL << 32);
  std::mt19937 b(0);
  std::cout << (a() == b()) << '\n';
}
```

A. `0`: the seeds are different, so the sequences differ
B. `1`
C. Unspecified
D. Ill-formed: the seed does not fit in `result_type`

**Answer (B):** `1`

**Why:** The single-value seed is reduced modulo 2^32 for `mt19937`, so `1 << 32` and `0` give the same state. Where `result_type` is 32 bits wide, the conversion of the argument already truncates it, and where it is wider the engine's own reduction does the same. The call is not ill-formed, since an integer converts implicitly. A 32-bit seed can select at most 2^32 of the engine's possible states.

### Question 6 [tricky] ([rand.dist.uni.int])

What does the C++ standard say about this program?

```cpp
#include <iostream>
#include <random>

int main() {
  std::mt19937 gen(1);
  std::uniform_int_distribution<int> d(6, 1);
  std::cout << d(gen) << '\n';
}
```

A. It prints an integer in `[1, 6]`, because the bounds are swapped
B. It throws `std::invalid_argument`
C. The program is ill-formed
D. Undefined behavior: `a <= b` is a precondition

**Answer (D):** Undefined behavior: `a <= b` is a precondition

**Why:** The distribution requires `a <= b`, and the constructor does not check or reorder its arguments. Violating a precondition is undefined behavior, so nothing in the standard promises the swapped range, an exception, or a diagnostic. Some implementations happen to produce numbers in the swapped range, which is exactly why the bug survives testing.

### Question 7 [standardese] ([rand.predef], [rand.eng.mers])

In C++23, what does this program print?

```cpp
#include <iostream>
#include <random>

int main() {
  std::mt19937 g;
  for (int i = 1; i < 10000; ++i) g();
  std::cout << g() << '\n';
}
```

A. `4123659995`
B. `3499211612`
C. Unspecified: the default seed is implementation-defined
D. `1043618065`

**Answer (A):** `4123659995`

**Why:** The standard fixes the default seed of `mt19937` at 5489 and requires the 10000th consecutive invocation of a default-constructed engine to produce 4123659995. The loop makes 9999 calls and the next one is the 10000th. The value 3499211612 is the first output of the default engine, and 1043618065 is the corresponding value for `minstd_rand0`.

### Question 8 [standardese] ([rand.dist.uni.int])

What does the C++23 standard say about instantiating `std::uniform_int_distribution<char>`?

```cpp
#include <random>

int main() {
  std::mt19937 g;
  std::uniform_int_distribution<char> d('a', 'z');
  (void)d(g);
}
```

A. It is well-formed and produces `char` values in `['a', 'z']`
B. The effect is undefined, because only the listed standard integer types other than the character types and `bool` are permitted
C. It is ill-formed, and every conforming compiler must reject it
D. It is implementation-defined, and each library must document its behavior

**Answer (B):** The effect is undefined, because only the listed standard integer types other than the character types and `bool` are permitted

**Why:** The distribution templates are defined only for the types `short`, `int`, `long`, `long long` and their unsigned counterparts; the effect of using any other type, including `char`, `bool` and the sized aliases for char types, is undefined. Libraries may reject it, as libc++ does with a `static_assert`, or accept it, as libstdc++ does, but neither is required. Use `int` and convert the result.

# Floating point and numerics

> The standard says very little about how floating point behaves, so IEEE 754 behaviour is something you check for, not something you get. This topic covers NaN and signed zero, conversions that are undefined, excess precision, and the library tools that behave well.

- **Source:** C++ Atlas (https://cppatlas.com/topics/floating-point-and-numerics)
- **Track:** Library utilities
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [basic.fundamental] (https://eel.is/c++draft/basic.fundamental), [conv.fpint] (https://eel.is/c++draft/conv.fpint), [conv.double] (https://eel.is/c++draft/conv.double), [expr.pre] (https://eel.is/c++draft/expr.pre), [expr.mul] (https://eel.is/c++draft/expr.mul), [expr.spaceship] (https://eel.is/c++draft/expr.spaceship), [cmp.partialord] (https://eel.is/c++draft/cmp.partialord), [numeric.limits.members] (https://eel.is/c++draft/numeric.limits.members), [charconv.to.chars] (https://eel.is/c++draft/charconv.to.chars), [charconv.from.chars] (https://eel.is/c++draft/charconv.from.chars), [numeric.ops.midpoint] (https://eel.is/c++draft/numeric.ops.midpoint), [c.math.lerp] (https://eel.is/c++draft/c.math.lerp)
- **cppreference links:** [Fundamental types (floating-point types)](https://en.cppreference.com/w/cpp/language/types), [std::numeric_limits<T>::is_iec559](https://en.cppreference.com/w/cpp/types/numeric_limits/is_iec559), [Floating-point conversions and exceptional values (implicit conversions)](https://en.cppreference.com/w/cpp/language/implicit_conversion), [std::to_chars](https://en.cppreference.com/w/cpp/utility/to_chars), [std::from_chars](https://en.cppreference.com/w/cpp/utility/from_chars), [std::midpoint](https://en.cppreference.com/w/cpp/numeric/midpoint), [std::lerp](https://en.cppreference.com/w/cpp/numeric/lerp), [Mathematical constants](https://en.cppreference.com/w/cpp/numeric/constants), [Extended floating-point types (header stdfloat)](https://en.cppreference.com/w/cpp/header/stdfloat), [FLT_EVAL_METHOD](https://en.cppreference.com/w/cpp/types/climits/FLT_EVAL_METHOD), [Common mathematical functions](https://en.cppreference.com/w/cpp/numeric/math)
- **Prerequisites:** fundamental-types-and-arithmetic-conversions, constant-expressions

## The one idea

C++ does not say that `double` is an IEEE 754 binary64 number. The core language only requires that the types `float`, `double` and `long double` hold a set of values where each set contains the one before, and that the value representation is implementation-defined. Everything you know about NaN, infinities, signed zero and round-to-nearest comes from the hardware and the compiler, not from the language.

The standard gives you one honest switch for asking. `std::numeric_limits<T>::is_iec559` is true when the type conforms to IEC 559, which is IEEE 754. You can `static_assert` on it, and that is the right way to document that a piece of code depends on IEEE behaviour.

> **Mental model.** A floating-point value is a point on a finite, uneven grid. Every operation computes an exact real answer and then snaps it to a nearby grid point. The standard leaves the grid and the snapping rule to the implementation, and `is_iec559` tells you the implementation chose the IEEE ones.

```cpp
#include <limits>

static_assert(std::numeric_limits<double>::is_iec559,
              "this code assumes IEEE 754 doubles");
static_assert(std::numeric_limits<double>::digits == 53);  // true for binary64
```

When `is_iec559` is true, `has_infinity`, `has_quiet_NaN` and `has_signaling_NaN` are true as well. Note also that division by zero is formally undefined in [expr.mul], including for floating-point operands. On an IEEE platform it yields an infinity or NaN in practice, which is why the `is_iec559` check matters before you rely on it.

## Why 0.1 + 0.2 is not 0.3

The decimal literal `0.1` has no finite binary expansion, so it is stored as the nearest binary64 value, which is slightly above one tenth. The same is true of `0.2` and `0.3`, each with its own small error. The sum of the first two is computed exactly and then rounded, and it lands one grid step above the grid point nearest to `0.3`.

```cpp
#include <cstdio>

int main() {
  double a = 0.1 + 0.2;
  std::printf("%d\n", a == 0.3);   // 0 on an IEEE binary64 platform
  std::printf("%.17g\n", a);       // 0.30000000000000004
}
```

The fix is never to compare computed floating-point values for equality unless you know the computation is exact. Compare with a tolerance chosen for the problem, which is relative for large magnitudes and absolute near zero. A single global epsilon is almost always wrong. `std::numeric_limits<double>::epsilon()` is the gap between 1.0 and the next value, so it is only a sensible tolerance for numbers near 1.

The grid is also uneven. Above 2 to the 24th power, `float` cannot represent every integer, so `16777216.0f + 1.0f` is `16777216.0f` again. Integers are exact in `double` only up to 2 to the 53rd power.

## NaN, ordering, and signed zero

A NaN is not equal to anything, including itself, and every ordered comparison with a NaN is false. The only comparison that is true is `!=`.

```cpp
#include <compare>
#include <limits>

int main() {
  double n = std::numeric_limits<double>::quiet_NaN();
  bool a = n == n;   // false
  bool b = n != n;   // true
  bool c = n < 1.0;  // false
  bool d = n >= 1.0; // false

  std::partial_ordering o = n <=> 1.0;
  bool u = (o == std::partial_ordering::unordered);  // true
  bool l = o < 0;    // false: unordered is not less
  bool g = o > 0;    // false: nor greater
  (void)a; (void)b; (void)c; (void)d; (void)u; (void)l; (void)g;
}
```

That is why `operator<=>` on a floating-point type returns `std::partial_ordering`, not `strong_ordering`. It has four values: less, equivalent, greater, and unordered. Because `unordered` compares false against every ordering test, `std::sort` with a plain `<` on data that contains a NaN breaks the strict weak ordering requirement, and the behaviour is undefined. Filter NaNs out first, or sort with `std::strong_order`, which is a total order that places NaNs consistently. The details of orderings belong to `three-way-comparison` and `strict-weak-ordering-and-comparators`.

> **Pitfall.** `std::max(a, b)` is defined with `<`. If `a` is a NaN, the comparison is false and the result depends on argument order. `std::fmax`, on the other hand, returns the non-NaN argument. Neither choice is wrong, but mixing them in one codebase gives results that change when a NaN appears.

Signed zero is the other trap. Under IEEE, `+0.0` and `-0.0` compare equal, yet they are different values with different bit patterns, and `std::signbit` and `std::copysign` can tell them apart. Functions such as `std::atan2`, and division in an IEEE environment, give different results for the two zeros. `<=>` treats them as `equivalent`, so a `bit_cast` to an integer is the way to ask whether two doubles are the same object, not just equal numbers.

## Rounding, precision, and `FLT_EVAL_METHOD`

The language lets an implementation evaluate floating-point operands and results in greater range and precision than the type requires, without changing the type. This is [expr.pre]. The macro `FLT_EVAL_METHOD` in `<cfloat>` reports what the implementation does: 0 means each operation is evaluated in its own type, and other values mean wider evaluation. Historic x87 builds used a wider format, which made `a + b == c` depend on whether the intermediate stayed in a register. On the arm64 machine used for the examples in this topic the value is 0.

Fused multiply-add is a modern relative of the same problem, and contraction is allowed whatever `FLT_EVAL_METHOD` says. A compiler that turns `a * b + c` into one fused instruction rounds once instead of twice, which changes the last bit of the result. In a test on this machine, both g++-16 and clang++ at `-O2` produced the fused answer for a carefully chosen input, and `-ffp-contract=off` produced the unfused one. If you need the same bits everywhere, call `std::fma` when you want one rounding, and disable contraction when you want two.

The rounding mode itself is dynamic state. The `<cfenv>` header lets you change it, but the compiler may assume the default mode unless the program says otherwise, so changing it casually is unreliable. The mode is not part of the type, and `std::numeric_limits<T>::round_style` describes the arithmetic's default.

## Conversions that are undefined

Converting a floating-point value to an integer truncates toward zero. If the truncated value does not fit in the destination type, the behaviour is undefined, whether the source is infinity, a NaN, or just a large finite number. This is [conv.fpint]. Converting between floating-point types is similar: a value in range but not exactly representable becomes an implementation-defined choice of one of the two neighbours, and a value out of range is undefined. In practice an IEEE platform gives an infinity, but the language does not promise it.

```cpp
constexpr int a = static_cast<int>(3.99);   // OK: 3
constexpr int b = static_cast<int>(-3.99);  // OK: -3, truncation toward zero

// constexpr int c = static_cast<int>(1e10);
// ill-formed: undefined behaviour is not a constant expression
```

Constant evaluation is a useful probe here. The commented line is rejected by both compilers because the conversion is not a constant expression. At run time the same code compiles and does whatever the hardware does, which is often saturation on arm64 and `INT_MIN` on x86.

Going the other way, from an integer to a floating-point type, an integer that is not exactly representable is rounded to one of the neighbours chosen by the implementation, and one that is out of range is undefined.

## The library tools that behave

`std::midpoint(a, b)` in `<numeric>`, since C++20, computes the average without overflowing. For integers the half-way case rounds toward the first argument, so `std::midpoint(1, 2)` is 1 and `std::midpoint(2, 1)` is 2. For floating-point arguments at most one inexact operation occurs.

`std::lerp(a, b, t)` in `<cmath>`, also C++20, interpolates and is specified to return exactly `a` at `t == 0` and exactly `b` at `t == 1`, to be finite for `t` in `[0, 1]`, to be monotonic in `t`, and to extrapolate for `t` outside that range. It is not the same as `a + t * (b - a)`, which fails to return `b` at `t == 1` for some inputs.

`std::to_chars` and `std::from_chars` in `<charconv>` are the correct way to move floating-point numbers through text. The plain `to_chars(first, last, value)` overload produces the shortest representation that `from_chars` will read back to exactly the same value. That is the round-trip guarantee, and the standard only provides it when both functions come from the same implementation. `from_chars` does not accept a leading plus sign or leading white space, it accepts `nan` and `inf`, and when the value is out of range it returns `result_out_of_range` and leaves the destination unmodified.

```cpp
#include <charconv>
#include <cstdio>

int main() {
  char buf[64];
  auto r = std::to_chars(buf, buf + sizeof buf, 0.1 + 0.2);
  *r.ptr = '\0';
  std::puts(buf);                  // 0.30000000000000004

  double back = 0;
  std::from_chars(buf, r.ptr, back);
  std::printf("%d\n", back == 0.1 + 0.2);  // 1: exact round trip

  double v = 7;
  const char s[] = "1e400";
  auto fr = std::from_chars(s, s + 5, v);
  // fr.ec == std::errc::result_out_of_range, and v is still 7
  (void)fr;
}
```

The constants in `<numbers>`, such as `std::numbers::pi` and `std::numbers::e`, come as variable templates such as `std::numbers::pi_v<float>`, plus plain `double` variables such as `std::numbers::pi`. You never need to write `3.14159` by hand.

## Constexpr math, extended types, and fast-math

Before C++23 most of `<cmath>` could not be used in constant expressions. C++23 made constexpr the functions that do not depend on the floating-point environment, among them `fabs`, `floor`, `ceil`, `fmod` and `fma`. C++26 extended this to most of the rest, including `sqrt`, which is not constexpr in C++23. GCC treats many built-ins as constant-foldable as an extension, so a compiler accepting a call is not evidence that the standard allows it.

C++23 also added optional extended floating-point types in `<stdfloat>`: `std::float16_t`, `std::float32_t`, `std::float64_t`, `std::float128_t` and `std::bfloat16_t`. An implementation declares each one through a macro such as `__STDCPP_FLOAT64_T__`. They are distinct types even when they have the same layout as a standard one, so `std::float64_t` is not `double`, and overloads and templates see them separately. On this machine, g++-16 provides all five.

`-ffast-math` is not a faster version of the standard. It is a family of compiler flags that licenses reassociation, ignores NaN and infinity, and assumes no signed zeros. Code that relies on NaN checks, `is_iec559` or exact rounding can silently change meaning. Treat the flag as leaving the standard, and keep it out of any code that handles NaNs or needs reproducible rounding.

## What to remember

- The standard does not require IEEE 754; use `static_assert(std::numeric_limits<T>::is_iec559)` to document the dependency.
- `0.1 + 0.2 != 0.3` because the literals and the sum are each rounded to the binary grid; compare with a problem-specific tolerance.
- A NaN is unequal to everything, and `<=>` on floating point yields `std::partial_ordering`, whose `unordered` value fails every ordering test.
- `+0.0 == -0.0`, but `signbit` and `copysign` see the difference.
- Excess precision and fused multiply-add are allowed, so results can differ between builds; `FLT_EVAL_METHOD` reports the evaluation format.
- Out-of-range float-to-integer conversion is undefined, and constant evaluation rejects it.
- `midpoint` and `lerp` avoid overflow and endpoint errors; integer `midpoint` rounds toward its first argument.
- `to_chars` and `from_chars` round-trip exactly, but only within one implementation.
- C++23 makes the environment-independent `<cmath>` functions constexpr and adds `<stdfloat>`; C++26 adds constexpr for most of the rest.
- `-ffast-math` abandons the semantics above.

## Concept Map Outline

- **Floating point and numerics:** The standard fixes little; IEEE behaviour is something you test for with is_iec559, not something you get.
  - **What the standard requires:** Only that float values are a subset of double values, which are a subset of long double; the representation is implementation-defined.
    - **is_iec559:** numeric_limits<T>::is_iec559 reports IEC 559 (IEEE 754) conformance; static_assert on it to document the dependency.
    - **Division by zero:** Formally undefined in [expr.mul]; IEEE platforms give an infinity or NaN.
    - **Extended types (C++23):** <stdfloat> adds optional float16_t to float128_t and bfloat16_t, each a distinct type from float, double and long double.
  - **Equality and ordering:** Floating-point comparison is not a total order, and equality is the wrong tool for computed values.
    - **0.1 + 0.2 != 0.3:** Each literal and the sum are rounded to the binary grid, so the sum lands one step from the nearest double to 0.3.
    - **NaN compares:** A NaN is unequal to everything including itself, and only != is true.
    - **partial_ordering:** <=> on floating point returns partial_ordering, whose unordered value fails less, equal and greater tests.
    - **Signed zero:** +0.0 equals -0.0, but signbit, copysign and a bit_cast can tell them apart.
  - **Precision and rounding:** Results can differ between builds because the standard permits wider evaluation and fused operations.
    - **Excess precision:** [expr.pre] lets operands and results use more range and precision than their type, without changing the type.
    - **FLT_EVAL_METHOD:** The <cfloat> macro that reports the evaluation format; 0 means each operation uses its own type.
    - **Contraction and fma:** A fused a*b+c rounds once; std::fma asks for that, and -ffp-contract=off forbids it.
  - **Conversions:** Narrowing from floating point can be undefined, and constant evaluation exposes it.
    - **Float to int:** Truncates toward zero; undefined when the result does not fit, including for infinities and NaNs.
    - **Float to float:** In range but inexact picks a neighbour, implementation-defined; out of range is undefined.
    - **Constant evaluation:** An out-of-range float-to-int conversion is not a constant expression, so constexpr rejects it.
  - **Library helpers:** Utilities that avoid the usual overflow, endpoint and text-conversion mistakes.
    - **midpoint:** Overflow-free average; integer results round toward the first argument.
    - **lerp:** Exact at t == 0 and t == 1, monotonic in t, and extrapolates outside the unit interval.
    - **to_chars and from_chars:** Shortest text that parses back exactly, guaranteed only within one implementation.
    - **numbers constants:** pi, e and friends as double variables, with _v variable templates for other types.
  - **Constexpr math and fast-math:** Which cmath functions work at compile time, and why optimization flags can leave the standard.
    - **C++23 constexpr cmath:** Functions independent of the floating-point environment, such as fabs, floor and fma, became constexpr.
    - **C++26 constexpr cmath:** Most remaining functions, including sqrt and sin, became constexpr in C++26.
    - **-ffast-math:** Licenses reassociation and ignoring NaN, infinity and signed zero; the program no longer follows the standard's rules.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.fundamental], [expr.pre])

Assume `double` is IEEE 754 binary64 and `FLT_EVAL_METHOD` is 0. What is printed?

```cpp
#include <cstdio>

int main() {
  double a = 0.1 + 0.2;
  std::printf("%d\n", a == 0.3);
}
```

A. 1
B. 0
C. Undefined behavior
D. Ill-formed: `==` on floating-point operands is not allowed

**Answer (B):** 0

**Why:** The literals `0.1`, `0.2` and `0.3` are each rounded to the nearest binary64 value, and the sum of the first two is rounded again. The result is `0.30000000000000004`, one grid step above the double nearest to `0.3`, so the comparison is false. Comparing floating-point values with `==` is allowed, it is just rarely what you want.

### Question 2 [warmup] ([expr.eq], [expr.rel])

Assume `double` is IEEE 754 binary64. What is printed?

```cpp
#include <cmath>
#include <cstdio>

int main() {
  double n = std::nan("");
  std::printf("%d%d%d%d\n", n == n, n != n, n < n, n >= n);
}
```

A. 1010
B. 0101
C. 0100
D. 1111

**Answer (C):** 0100

**Why:** A NaN is unordered with everything, itself included. So `n == n` is 0, `n != n` is 1, and the ordered comparisons `n < n` and `n >= n` are both 0. Only `!=` is true for a NaN, which is the trap in the `0101` option: `>=` is not the negation of `<` when NaNs exist.

### Question 3 [warmup] ([basic.fundamental])

Assume `double` is IEEE 754 binary64. What is printed?

```cpp
#include <cmath>
#include <cstdio>

int main() {
  double x = -0.0, y = 0.0;
  std::printf("%d %g\n", x == y, std::copysign(1.0, x));
}
```

A. 1 1
B. 0 -1
C. 0 1
D. 1 -1

**Answer (D):** 1 -1

**Why:** Negative zero compares equal to positive zero, so `x == y` is 1. But it keeps its sign bit, and `std::copysign(1.0, x)` copies that sign onto 1.0, giving -1. The option `1 1` assumes the two zeros are the same value in every respect, which holds only for comparison.

### Question 4 [tricky] ([expr.spaceship], [cmp.partialord])

Assume `double` is IEEE 754 binary64. What is printed?

```cpp
#include <cmath>
#include <compare>
#include <cstdio>

int main() {
  auto o = std::nan("") <=> 1.0;
  std::printf("%d%d%d%d\n", o < 0, o == 0, o > 0,
              o == std::partial_ordering::unordered);
}
```

A. 0000
B. 0001
C. 1001
D. Ill-formed: `double` has no `operator<=>`

**Answer (B):** 0001

**Why:** `<=>` on `double` yields `std::partial_ordering`. With a NaN operand the result is `unordered`. That value is not less than, equivalent to, or greater than zero, so the first three tests print 0, and only the comparison with `std::partial_ordering::unordered` is true. The option `0000` forgets that `unordered` is a distinct, comparable value.

### Question 5 [tricky] ([conv.fpint], [expr.const])

In C++23, what is the status of this declaration?

```cpp
constexpr int i = static_cast<int>(1e10);

int main() { return 0; }
```

A. Well-formed, and `i` is `INT_MAX`
B. Well-formed, and `i` wraps modulo 2^32
C. Well-formed, and `i` has an implementation-defined value
D. Ill-formed: the initializer is not a constant expression

**Answer (D):** Ill-formed: the initializer is not a constant expression

**Why:** Converting a floating-point value to an integer type is undefined when the truncated value is not representable in the destination. Undefined behavior is never a constant expression, so a `constexpr` variable cannot be initialized this way and the compiler must diagnose it. Saturation or wraparound at run time is what some hardware does, not something the language promises.

### Question 6 [tricky] ([numeric.ops.midpoint])

In C++20 or later, what is printed?

```cpp
#include <cstdio>
#include <numeric>

int main() {
  std::printf("%d %d\n", std::midpoint(0, 3), std::midpoint(3, 0));
}
```

A. 1 1
B. 2 1
C. 1 2
D. 2 2

**Answer (C):** 1 2

**Why:** `std::midpoint(a, b)` for integers computes the half-way value without overflow, and when the sum is odd the result is rounded toward the first argument. The mathematical midpoint of 0 and 3 is 1.5, so `midpoint(0, 3)` is 1 and `midpoint(3, 0)` is 2. The answer `1 1` is what a truncating `(a + b) / 2` would print for both calls.

### Question 7 [standardese] ([basic.fundamental], [expr.mul], [numeric.limits.members])

Which statement about `double` does the C++23 standard guarantee on every conforming implementation?

A. It has a 53-bit significand
B. Every value of type `float` is also a value of type `double`
C. Dividing by zero produces an infinity
D. It has both an infinity and a quiet NaN

**Answer (B):** Every value of type `float` is also a value of type `double`

**Why:** [basic.fundamental] requires that the set of values of `float` is a subset of those of `double`, which in turn is a subset of those of `long double`. It leaves the representation implementation-defined. The significand width, the existence of an infinity or NaN (check `has_infinity` and `has_quiet_NaN`), and the meaning of division by zero (undefined in [expr.mul]) are all things you can only rely on when `is_iec559` says so.

### Question 8 [standardese] ([charconv.to.chars], [charconv.from.chars])

A program writes a `double` with the overload `std::to_chars(first, last, value)` that takes no format or precision, and another program parses the text with `std::from_chars`. What does the standard guarantee about recovering the exact value?

A. It is guaranteed only when both calls come from the same implementation
B. It is guaranteed for any pair of conforming implementations
C. It is guaranteed only if the writer passes precision 17
D. Nothing is guaranteed: the text is only an approximation

**Answer (A):** It is guaranteed only when both calls come from the same implementation

**Why:** The no-argument overload chooses the shortest representation that `from_chars` reads back to exactly the same value, but the standard attaches that guarantee to the same implementation. Passing a precision is not needed for the guarantee, which is why the precision-17 habit from `printf` is unnecessary here. The last option is wrong because the same-implementation round trip is exact.

# Bit manipulation

> C++20 gave bits a real library in the header bit, and it also pinned down shifts on signed numbers. The traps that remain are shift counts, integer promotion on small types, and the preconditions of a few functions.

- **Source:** C++ Atlas (https://cppatlas.com/topics/bit-manipulation)
- **Track:** Library utilities
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [bit] (https://eel.is/c++draft/bit), [bit.cast] (https://eel.is/c++draft/bit.cast), [bit.byteswap] (https://eel.is/c++draft/bit.byteswap), [bit.endian] (https://eel.is/c++draft/bit.endian), [bit.pow.two] (https://eel.is/c++draft/bit.pow.two), [bit.rotate] (https://eel.is/c++draft/bit.rotate), [bit.count] (https://eel.is/c++draft/bit.count), [expr.shift] (https://eel.is/c++draft/expr.shift), [expr.unary.op] (https://eel.is/c++draft/expr.unary.op), [conv.prom] (https://eel.is/c++draft/conv.prom), [class.bit] (https://eel.is/c++draft/class.bit), [support.types.byteops] (https://eel.is/c++draft/support.types.byteops)
- **cppreference links:** [Bit manipulation (header bit)](https://en.cppreference.com/w/cpp/header/bit), [std::bit_cast](https://en.cppreference.com/w/cpp/numeric/bit_cast), [std::popcount](https://en.cppreference.com/w/cpp/numeric/popcount), [std::bit_ceil](https://en.cppreference.com/w/cpp/numeric/bit_ceil), [std::rotl](https://en.cppreference.com/w/cpp/numeric/rotl), [std::byteswap](https://en.cppreference.com/w/cpp/numeric/byteswap), [std::endian](https://en.cppreference.com/w/cpp/types/endian), [Arithmetic operators (shift operators)](https://en.cppreference.com/w/cpp/language/operator_arithmetic), [std::byte](https://en.cppreference.com/w/cpp/types/byte), [Bit-field](https://en.cppreference.com/w/cpp/language/bit_field)
- **Prerequisites:** fundamental-types-and-arithmetic-conversions, strict-aliasing-and-undefined-behavior

## The one idea

Bit work in C++ goes wrong in three places: the operand is narrower than `int` and gets promoted, the shift count is out of range, or the function has a precondition that nobody read. The `<bit>` header, added in C++20, removes most of the hand-written loops and compiler intrinsics. What is left are those three traps.

> **Mental model.** Treat every integer as a fixed-width row of bits, but remember that arithmetic and shifts first widen anything smaller than `int` to `int`. The `<bit>` functions skip that step: they look at the width of the exact type you pass.

Since C++20 the language also says that signed integers use two's complement. That is why the rules for shifting signed values could finally be written as plain arithmetic.

## What `<bit>` offers

The counting and rotating functions work on unsigned integer types only: `unsigned char`, `unsigned short`, `unsigned int`, the longer unsigned types, and extended unsigned types. They do not accept signed types, plain `char`, `bool`, `char8_t`, `char16_t`, `char32_t` or `wchar_t`. Calling `std::popcount(1)` is rejected at compile time because `1` is an `int`.

```cpp
#include <bit>
#include <cstdint>
#include <cstdio>

int main() {
  std::printf("%d\n", std::popcount(0b1011u));            // 3
  std::printf("%d\n", std::countl_zero(1u));              // 31 for a 32-bit unsigned int
  std::printf("%d\n", std::countl_zero(std::uint8_t{1})); // 7: the width of uint8_t, not of int
  std::printf("%d\n", std::countr_zero(8u));              // 3
  std::printf("%d\n", std::bit_width(255u));              // 8
  std::printf("%d\n", std::has_single_bit(0u));           // 0: zero is not a power of two
}
```

The second and third lines show the point of the mental model. `countl_zero` counts from the top of the type you gave it, not from the top of an `int`.

`rotl` and `rotr` rotate within the width of the type, and a negative count rotates the other way, so `std::rotl(x, -1)` equals `std::rotr(x, 1)`. Unlike a built-in shift, a rotate count of any value is defined.

```cpp
#include <bit>
#include <cstdint>

static_assert(std::rotl(std::uint8_t{0x81}, 1) == 0x03);
static_assert(std::rotl(std::uint8_t{0x81}, -1) == 0xC0);
static_assert(std::byteswap(std::uint16_t{0x1234}) == 0x3412);  // C++23
```

The power-of-two helpers are `has_single_bit`, `bit_floor`, `bit_ceil` and `bit_width`. `bit_floor(37u)` is 32, `bit_ceil(37u)` is 64, and `bit_width(0u)` is 0. `bit_floor(0)` is 0, and `bit_ceil(0)` is 1.

> **Standardese.** [bit.pow.two] says `bit_ceil(x)` is the smallest power of two not smaller than `x`, and that the behaviour is undefined if that value is not representable in the type. So `bit_ceil(0x80000001u)` is undefined for a 32-bit `unsigned`, and because the function is `constexpr`, constant evaluation rejects the call instead of returning a wrapped value.

`std::byteswap`, added in C++23, reverses the bytes of any integer type, signed ones included. It does not know about endianness. To convert between a wire order and the host order, compare `std::endian::native` against `std::endian::little` or `std::endian::big`. If `native` equals neither, the platform is mixed-endian, which is rare but allowed.

## `bit_cast`

`std::bit_cast<To>(from)` reinterprets the object representation of `from` as a value of type `To`. Both types must have the same size and be trivially copyable, or the call does not compile. It is `constexpr` when neither type contains a pointer, a union, a reference, or a volatile member, which makes it the sanctioned way to look inside a float in a constant expression.

```cpp
#include <bit>
#include <cstdint>

// Assumes IEEE binary32 float and a 32-bit unsigned.
static_assert(std::bit_cast<std::uint32_t>(1.0f) == 0x3f800000u);
// std::bit_cast<float>(std::uint64_t{1});  // ill-formed: sizes differ
```

Unlike `reinterpret_cast`, `bit_cast` creates a new object, so there is no aliasing problem. The `strict-aliasing-and-undefined-behavior` topic explains why `*reinterpret_cast<uint32_t*>(&f)` is not equivalent. If some bit pattern in the source does not correspond to a valid value of `To`, for example when casting arbitrary bytes to `bool`, the behaviour is undefined.

## Shifts: the counts

A shift expression has undefined behaviour when the right operand is negative or is greater than or equal to the width of the promoted left operand. This holds for `<<` and `>>`, signed and unsigned, and it is what makes `1u << 32` undefined for a 32-bit `unsigned`. The result is not zero, and nothing else is promised either.

```cpp
// constexpr unsigned a = 1u << 32;
// ill-formed: shift count >= width, so not a constant expression

constexpr unsigned mask(unsigned n) {
  return n == 0 ? 0u : ~0u >> (32 - n);  // n == 32 gives all ones; 0 must be handled
}
```

The classic form `(1u << n) - 1` for the low `n` bits fails at `n == 32`. Guard the edge cases explicitly, as the function above does for zero.

The type of the result is the promoted type of the left operand alone. The type of the count does not matter.

## Shifts: signedness and promotion

Right shift of a negative signed number was implementation-defined before C++20. Since C++20 it is the arithmetic shift: the result rounds toward negative infinity. That differs from division, which truncates toward zero.

```cpp
#include <cstdio>

int main() {
  std::printf("%d %d\n", -7 >> 1, -7 / 2);  // -4 -3 in C++20 and later
  int a = -1;
  std::printf("%d\n", a << 3);              // -8, well-defined since C++20
}
```

Left shift of a signed value used to be undefined for a negative left operand, and for results that did not fit even in the unsigned counterpart type. Since C++20 the result is the mathematical product reduced modulo 2 to the power of the width, interpreted as signed. So `-1 << 3` is `-8`, and `1 << 31` is `INT_MIN` for a 32-bit `int`. The count rules above still apply.

Integer promotion is the second trap. Each operand of a shift or bitwise operator is promoted separately, so a `std::uint8_t` or `unsigned short` becomes `int` first.

```cpp
#include <cstdint>
#include <cstdio>

int main() {
  std::uint8_t b = 0x0F;
  std::printf("%d\n", ~b);                   // -16, not 240: ~ works on the promoted int
  std::printf("%d\n", ~b == 0xF0);           // 0
  std::printf("%d\n", std::uint8_t(~b));     // 240: convert back to the narrow type
  std::uint8_t c = 0x80;
  std::printf("%d\n", c << 24);              // -2147483648: promoted to int, defined in C++20
}
```

Assume 32-bit `int` for those results. The fix is to convert back to the narrow type after the operation, or to work in `unsigned` throughout. The promotion rules themselves belong to `fundamental-types-and-arithmetic-conversions`.

> **Pitfall.** Shifting a `uint8_t` or `unsigned short` left is not an unsigned operation. The operand is promoted to `int`, so the result of `std::uint8_t{0x80} << 24` is the negative `int` `INT_MIN`, not the unsigned value 2147483648.

## Masks, `std::byte` and bit-fields

For raw memory, `std::byte` is an `enum class : unsigned char` that supports the bitwise operators and shifts but no arithmetic. That stops you adding two bytes by accident. Convert with `std::to_integer<int>(b)`, and build a byte by list-initializing from a constant.

```cpp
#include <cstddef>

constexpr std::byte lo{0x0F};
constexpr std::byte hi = lo << 4;               // 0xF0, and the type stays std::byte
static_assert(std::to_integer<int>(hi) == 240);
static_assert((hi | lo) == std::byte{0xFF});
```

Reading multi-byte values from a buffer is where bit work, promotion and endianness meet. The portable way to decode a big-endian value is with shifts, which give the same answer on every host. Each byte is widened to `std::uint32_t` before it is shifted, because shifting the byte directly would promote it to `int` and push the top byte into the sign bit. When the value is already sitting in an integer in network order, `std::endian::native` selects whether a `std::byteswap` is needed.

```cpp
#include <bit>
#include <cstddef>
#include <cstdint>

constexpr std::uint32_t load_be32(const std::byte* p) {
  return (std::uint32_t(p[0]) << 24) | (std::uint32_t(p[1]) << 16) |
         (std::uint32_t(p[2]) << 8)  |  std::uint32_t(p[3]);
}

constexpr std::uint32_t be_to_host(std::uint32_t v) {  // byteswap is C++23
  if constexpr (std::endian::native == std::endian::little) return std::byteswap(v);
  else return v;
}
```

The first function never mentions endianness, which is the point: arithmetic on values is host-independent, and only the interpretation of raw memory depends on the host.

Bit-fields look convenient, but the order of allocation, whether a field may straddle a storage unit, and how the compiler packs them are implementation-defined. Use them for compact in-memory flags, and use explicit shifts and masks for anything that must match a file format or a protocol. The standard does not promise that two compilers produce the same layout.

## What to remember

- `<bit>` functions need unsigned integer types and look at the width of the exact type; `countl_zero(uint8_t{1})` is 7.
- `bit_ceil` is undefined when the result does not fit, and constant evaluation catches it. `bit_floor(0)` is 0 and `bit_ceil(0)` is 1.
- `rotl` and `rotr` accept any count; a negative count reverses the direction.
- `std::byteswap` is C++23 and works on any integer type; `std::endian` is the way to ask about host order.
- `bit_cast` needs equal sizes and trivially copyable types, works in constant expressions, and avoids the aliasing rules.
- A shift count that is negative or at least the promoted width is undefined, for both directions.
- Since C++20, right shift of a negative number is arithmetic, and left shift of a signed number is modular.
- Operands smaller than `int` are promoted before `~`, `<<`, `>>` and the other bit operators.
- Use `std::byte` for raw bytes, and avoid bit-fields for external formats.

## Concept Map Outline

- **Bit manipulation:** The bit header counts and rotates by exact type width; shifts and promotion are where the surprises live.
  - **Counting and rotating:** These functions take unsigned types only and use the width of the exact type, with no promotion to int.
    - **popcount:** Counts the set bits of an unsigned integer.
    - **countl_zero, countr_zero:** Count leading or trailing zeros in the width of the argument type; countl_zero(uint8_t{1}) is 7.
    - **rotl and rotr:** Rotate within the type width; any count is allowed and a negative count reverses direction.
  - **Power-of-two helpers:** has_single_bit, bit_width, bit_floor and bit_ceil describe a value's relation to powers of two.
    - **has_single_bit:** True only for powers of two, so false for zero.
    - **bit_floor, bit_width:** bit_floor(0) is 0, bit_width(0) is 0, and bit_floor(37u) is 32.
    - **bit_ceil precondition:** Undefined if the result does not fit the type; constant evaluation rejects it.
  - **Reinterpreting bytes:** bit_cast, byteswap and endian handle object representation without aliasing violations.
    - **bit_cast:** Needs equal sizes and trivially copyable types; constexpr unless pointers, unions or references are involved.
    - **byteswap (C++23):** Reverses the bytes of any integer type and knows nothing about the host order.
    - **std::endian:** little, big and native describe byte order; native may equal neither on a mixed-endian platform.
  - **Shift counts:** The right operand has to be within range for both shift directions.
    - **Count out of range:** A negative count or one at least the promoted width is undefined, for signed and unsigned alike.
    - **Result type:** The result has the promoted type of the left operand; the count's type does not matter.
    - **Mask pitfall:** (1u << n) - 1 fails at n equal to the width; guard the edge cases.
  - **Signedness and promotion:** Narrow operands become int before shifts and bitwise operators, and C++20 tightened signed shifts.
    - **Right shift, C++20:** Negative values shift arithmetically, rounding toward negative infinity, so -7 >> 1 is -4.
    - **Left shift, C++20:** Signed left shift is modular and two's complement, so -1 << 3 is -8.
    - **Promotion trap:** ~uint8_t{15} is the int -16, and uint8_t{0x80} << 24 is a negative int.
    - **Two's complement:** C++20 requires signed integers to use two's complement.
  - **Bytes and bit-fields:** Use std::byte for raw memory and be wary of bit-fields in external formats.
    - **std::byte:** Supports bitwise operators and shifts, no arithmetic; convert with std::to_integer.
    - **Bit-field layout:** Allocation order and straddling are implementation-defined, so use masks for wire formats.

## Standardese Quiz Questions

### Question 1 [warmup] ([bit.pow.two])

In C++20 or later, assuming a 32-bit `unsigned int`, what is printed?

```cpp
#include <bit>
#include <cstdio>

int main() {
  std::printf("%d %d %u %u\n", std::has_single_bit(0u), std::has_single_bit(8u),
              std::bit_floor(37u), std::bit_ceil(37u));
}
```

A. 1 1 32 64
B. 0 0 32 38
C. 0 1 32 64
D. 0 1 37 37

**Answer (C):** 0 1 32 64

**Why:** Zero is not a power of two, so `has_single_bit(0u)` is false, and 8 has a single set bit. `bit_floor(37u)` is the largest power of two not above 37, which is 32, and `bit_ceil(37u)` is the smallest one not below it, which is 64. The option starting with 1 treats zero as a power of two.

### Question 2 [warmup] ([expr.shift], [expr.mul])

In C++20 or later, assuming a 32-bit `int`, what is printed?

```cpp
#include <cstdio>

int main() {
  std::printf("%d %d\n", -7 >> 1, -7 / 2);
}
```

A. -3 -3
B. -4 -3
C. -4 -4
D. -3 -4

**Answer (B):** -4 -3

**Why:** Since C++20, right shift of a negative signed value is the arithmetic shift, which rounds toward negative infinity, so `-7 >> 1` is -4. Division truncates toward zero, so `-7 / 2` is -3. Before C++20 the shift result was implementation-defined, and the tempting `-3 -3` assumes the two operators agree.

### Question 3 [warmup] ([bit.rotate])

In C++20 or later, what is printed?

```cpp
#include <bit>
#include <cstdint>
#include <cstdio>

int main() {
  std::uint8_t x = 0x81;
  std::printf("%d %d\n", std::rotl(x, 1), std::rotl(x, -1));
}
```

A. 258 192
B. 3 3
C. Ill-formed: `rotl` does not accept `std::uint8_t`
D. 3 192

**Answer (D):** 3 192

**Why:** `rotl` rotates within the width of its argument type, which is 8 bits here, so 0x81 rotated left by one is 0x03 because the top bit wraps around. A negative count rotates the other way, so `rotl(x, -1)` is 0xC0, which is 192. The answer 258 treats the operand as an `int` and lets the bit escape.

### Question 4 [tricky] ([bit.count])

In C++20 or later, assuming a 32-bit `unsigned int`, what is printed?

```cpp
#include <bit>
#include <cstdint>
#include <cstdio>

int main() {
  std::printf("%d %d\n", std::countl_zero(std::uint8_t{1}), std::countl_zero(1u));
}
```

A. 31 31
B. 7 7
C. 7 31
D. 8 32

**Answer (C):** 7 31

**Why:** The `<bit>` functions look at the width of the exact type, so `countl_zero(std::uint8_t{1})` counts the seven leading zeros of an 8-bit value, and `countl_zero(1u)` counts 31 of a 32-bit value. Unlike the built-in operators, they do not promote a narrow operand to `int` first, which is why `31 31` is wrong.

### Question 5 [tricky] ([expr.unary.op], [conv.prom])

Assume a 32-bit `int`. What is printed?

```cpp
#include <cstdint>
#include <cstdio>

int main() {
  std::uint8_t b = 0x0F;
  std::printf("%d\n", ~b);
}
```

A. 240
B. -16
C. -241
D. Undefined behavior: `~` overflows

**Answer (B):** -16

**Why:** A `std::uint8_t` operand of `~` is promoted to `int` first, so `~b` complements all 32 bits of the value 15, giving -16. The result is not converted back to 8 bits unless you write `std::uint8_t(~b)`, which is what the tempting answer 240 assumes. There is no overflow, since complementing an `int` is always defined.

### Question 6 [tricky] ([expr.shift])

In C++20, assuming a 32-bit `int`, what does this program print?

```cpp
#include <cstdio>

int main() {
  int a = -1;
  std::printf("%d\n", a << 3);
}
```

A. -8
B. Undefined behavior: the left operand is negative
C. 8
D. Implementation-defined

**Answer (A):** -8

**Why:** Since C++20 a left shift of a signed value is defined modulo 2 to the power of the width, and the two's complement result is read back as signed. For `-1 << 3` that gives -8. Before C++20 a negative left operand made the shift undefined, which is the answer a C++17 reader would give, and it is not a matter of implementation choice now.

### Question 7 [standardese] ([expr.shift], [expr.const])

In C++23, assuming a 32-bit `unsigned int`, what is the status of this declaration?

```cpp
constexpr unsigned x = 1u << 32;

int main() { return 0; }
```

A. Well-formed, and `x` is 0
B. Well-formed, and `x` is 1
C. Ill-formed: the initializer is not a constant expression
D. Well-formed, and `x` has an unspecified value

**Answer (C):** Ill-formed: the initializer is not a constant expression

**Why:** A shift whose count is greater than or equal to the width of the promoted left operand has undefined behaviour, even for unsigned types. Undefined behaviour is never allowed in a constant expression, so initializing a `constexpr` variable this way is ill-formed. Shifting out all the bits to leave zero is a common expectation, and it is not what the language says.

### Question 8 [standardese] ([bit.pow.two], [expr.const])

In C++23, assuming a 32-bit `unsigned int`, what is the status of this program?

```cpp
#include <bit>

static_assert(std::bit_ceil(0x80000001u) == 0);

int main() { return 0; }
```

A. `bit_ceil` returns 0 and the assertion passes
B. `bit_ceil` returns 0x80000000 and the assertion fails
C. `bit_ceil` throws `std::overflow_error`
D. The call has undefined behaviour, so it is not a constant expression and the program is ill-formed

**Answer (D):** The call has undefined behaviour, so it is not a constant expression and the program is ill-formed

**Why:** The next power of two above 0x80000001 would be 2 to the 32nd power, which does not fit in a 32-bit `unsigned int`. [bit.pow.two] makes that case undefined behaviour, and a `constexpr` function may not be used with undefined behaviour in constant evaluation, so the `static_assert` is rejected. Wraparound to 0 is what a hand-written loop would give, but the library function promises nothing of the kind.

# Character types and Unicode

> C++ has six character types and four literal prefixes, but only the library's code-unit view of text. Knowing what a char holds, which encoding a literal gets, and what counts as a character for the reader is what keeps Unicode code correct.

- **Source:** C++ Atlas (https://cppatlas.com/topics/character-types-and-unicode)
- **Track:** Library utilities
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [basic.fundamental] (https://eel.is/c++draft/basic.fundamental), [lex.charset] (https://eel.is/c++draft/lex.charset), [lex.phases] (https://eel.is/c++draft/lex.phases), [lex.ccon] (https://eel.is/c++draft/lex.ccon), [lex.string] (https://eel.is/c++draft/lex.string), [lex.universal.char] (https://eel.is/c++draft/lex.universal.char), [lex.string.uchar] (https://eel.is/c++draft/lex.string.uchar), [format.string.std] (https://eel.is/c++draft/format.string.std), [depr.locale.stdcvt] (https://eel.is/c++draft/depr.locale.stdcvt), [depr.conversions] (https://eel.is/c++draft/depr.conversions)
- **cppreference links:** [Fundamental types](https://en.cppreference.com/w/cpp/language/types), [Character literal](https://en.cppreference.com/w/cpp/language/character_literal), [String literal](https://en.cppreference.com/w/cpp/language/string_literal), [Escape sequences](https://en.cppreference.com/w/cpp/language/escape), [Character sets and encodings](https://en.cppreference.com/w/cpp/language/charset), [std::isalpha](https://en.cppreference.com/w/cpp/string/byte/isalpha), [std::codecvt_utf8](https://en.cppreference.com/w/cpp/locale/codecvt_utf8), [Format specification](https://en.cppreference.com/w/cpp/utility/format/spec), [std::text_encoding](https://en.cppreference.com/w/cpp/text/text_encoding)
- **Prerequisites:** fundamental-types-and-arithmetic-conversions, strings-and-string-view

## The one idea

A C++ character type is an integer type that holds one **code unit**, which is a piece of an encoded string, not necessarily a character that a person would point to. A `char` of a UTF-8 string is one byte. A `char16_t` of a UTF-16 string is half of a surrogate pair for most emoji. Everything in this topic follows from asking which of three things you are counting: code units, code points, or what a reader sees as one character, called a grapheme cluster.

> **Mental model.** `std::string`, `std::u8string`, `std::u16string` and `std::u32string` are arrays of code units. The standard library, apart from a few narrow facilities, never looks inside them. Anything that needs code points or grapheme clusters, such as normalization, case folding or segmentation, is your job or a third-party library's.

## The six character types

`char`, `signed char` and `unsigned char` are three distinct types, even though `char` has the same representation as one of the other two. Which one is implementation-defined, and portable code must not rely on it. In practice `char` is signed on x86 Linux and unsigned on ARM Linux, and a plain `char` holding a byte above 127 gives a negative number where it is signed.

```cpp
#include <type_traits>

// All three are distinct types in every implementation.
static_assert(!std::is_same_v<char, signed char>);
static_assert(!std::is_same_v<char, unsigned char>);
```

`wchar_t` is the wide character type. Its size and its encoding are implementation-defined: it is 32 bits with UTF-32 on most Unix systems and 16 bits with UTF-16 on Windows. For that reason `wchar_t` is a poor choice for portable text.

`char16_t` and `char32_t` came with C++11 and are meant for UTF-16 and UTF-32 code units. Each has the same size, signedness and alignment as `std::uint_least16_t` and `std::uint_least32_t`. `char8_t` arrived in C++20 for UTF-8 code units, with the same size, signedness and alignment as `unsigned char`. It is a separate type, and it does not get the permission that `char`, `unsigned char` and `std::byte` have to alias other objects.

## Literal prefixes and their types

Each prefix selects an encoding and a type. The prefixes are `u8`, `u`, `U` and `L`, plus no prefix for ordinary literals.

| Literal | Element type | Encoding |
| --- | --- | --- |
| `"abc"` | `char` | ordinary literal encoding, implementation-defined |
| `u8"abc"` | `char8_t` since C++20, `char` before | UTF-8 |
| `u"abc"` | `char16_t` | UTF-16 |
| `U"abc"` | `char32_t` | UTF-32 |
| `L"abc"` | `wchar_t` | wide literal encoding, implementation-defined |

The ordinary and wide literal encodings are what the compiler uses when it writes your string into the program. GCC and Clang default to UTF-8, and you can change it with options such as GCC's `-fexec-charset`. The execution environment may have a completely different idea of text at run time, which is why printing a "UTF-8" literal can still produce garbage on a terminal configured differently.

```cpp
#include <iterator>

// Counting code units, not characters (the final element is the terminator).
constexpr auto a = std::size(u8"é");        // 3: U+00E9 is two UTF-8 code units
constexpr auto b = std::size(u"\U0001F600");     // 3: surrogate pair, two UTF-16 units
constexpr auto c = std::size(U"\U0001F600");     // 2: one UTF-32 unit
static_assert(a == 3 && b == 3 && c == 2);
```

A character literal holds a single code unit. `u'\U0001F600'` is ill-formed in C++23, because the code point needs two UTF-16 code units, while `U'\U0001F600'` is fine.

### The `char8_t` break

C++20 changed the type of UTF-8 literals from `const char` arrays to `const char8_t` arrays. Code that worked in C++17 stops compiling.

```cpp
// const char* p = u8"abc";
// OK in C++17, ill-formed in C++20: const char8_t* does not convert to const char*

// std::cout << u8"abc";
// OK in C++17, ill-formed in C++20: the overload for const char8_t* is deleted
```

Fixes are to use `std::u8string` and `std::u8string_view`, to cast through `reinterpret_cast<const char*>` where you must pass the bytes to a `char` API, or to drop the `u8` prefix and rely on an ordinary literal encoding of UTF-8. GCC has `-fno-char8_t` as an escape hatch while you migrate. Note that `char8_t` has no stream output at all, so UTF-8 text in iostreams still needs a `char` view.

> **Standardese.** [lex.ccon] says a character literal with a `u`, `U` or `u8` prefix must be encodable as a single code unit of its type, and in C++23 a literal that is not is ill-formed. [lex.string] gives each string prefix its element type and encoding, which is why `u8"..."` changed type in C++20 without any change to its bytes.

## Source, execution, and escapes

Three encodings are in play when you compile: the encoding of the source file, the ordinary literal encoding, and the encoding of the program's locale at run time. Before C++23 the standard talked about a basic source character set and an implementation-defined mapping to the execution set. C++23 reworked this around the translation character set, which is Unicode, and the ordinary and wide literal encodings. It also requires implementations to support UTF-8 source files.

Escapes let you avoid the question entirely for the source side. A universal-character-name, `\u` followed by four hex digits or `\U` followed by eight, names a code point whatever the source encoding is. C++23 added more forms.

```cpp
const char8_t* a = u8"α";                     // alpha, as a universal-character-name
const char8_t* b = u8"\N{GREEK SMALL LETTER ALPHA}"; // C++23: named escape
const char8_t* c = u8"\u{3b1}";                    // C++23: delimited escape
const char*    d = "\x{41}\o{102}";                // C++23: delimited hex and octal, "AB"
```

The delimited and named forms are useful because they have no length limit and the name documents the intent. The distinction between `\x41` and `A` matters: the first writes a raw code unit value, while the second names a code point and is encoded according to the literal's encoding.

## `<cctype>` and the negative char

The functions in `<cctype>`, such as `std::isalpha` and `std::toupper`, take an `int`. The argument must be representable as an `unsigned char` or equal `EOF`. Otherwise the behaviour is undefined. On a platform where `char` is signed, a byte such as 0xE9 becomes a negative `int`, so passing a plain `char` straight in is undefined.

```cpp
#include <cctype>

bool is_letter(char c) {
  return std::isalpha(static_cast<unsigned char>(c));  // the required cast
}
```

Even with the cast, `<cctype>` works one byte at a time in the current C locale. It cannot classify a multibyte UTF-8 character, and `std::toupper` cannot turn one code unit into two, so it cannot map `ß` to `SS`. For Unicode-aware classification and case mapping you need a library such as ICU.

> **Pitfall.** The cast to `unsigned char` fixes the undefined behaviour, not the model. `<cctype>` still classifies single bytes, so a UTF-8 text with accented letters gets misclassified even though no rule is broken.

## Code units, code points, grapheme clusters

The same text can have different lengths depending on what you count. The letter é can be one code point, U+00E9, or two: `e` followed by the combining acute accent U+0301. A reader sees one character either way.

```cpp
#include <string>

std::u8string s1 = u8"é";       // size() == 2 code units, 1 code point, 1 grapheme cluster
std::u8string s2 = u8"é";      // size() == 3 code units, 2 code points, 1 grapheme cluster
```

`size()` on any `basic_string` counts code units. Indexing, `find`, `substr` and comparisons are all by code unit too, so they can cut a multi-unit character in half, and `s1 == s2` is false even though they display the same. Normalization, collation and segmentation are not in the standard library.

The one place the library does look at graphemes is `std::format`. Its width and precision are measured in estimated terminal columns, not code units. For a string in a Unicode encoding, implementations should treat each extended grapheme cluster as 2 columns when it starts with a wide or fullwidth code point and 1 otherwise. The method is unspecified in general, so portable code should not depend on exact padding.

```cpp
#include <format>

// With a UTF-8 ordinary literal encoding, in libstdc++ 16:
auto w = std::format("{:>4}", "日");   // two spaces then the character: width 2
auto g = std::format("{:>4}", "é");  // three spaces: one grapheme cluster, width 1
```

Precision truncates a string to a prefix of whole clusters whose estimated width fits, so with that estimate a precision of 1 applied to a width-2 character yields an empty string.

## Conversions and `std::text_encoding`

`<codecvt>` and `std::wstring_convert` were the standard's UTF converters. Both were deprecated in C++17, and cppreference lists them as removed in C++26. Libstdc++ 16 still ships them, with deprecation warnings. The replacement in the standard is thinner: the C-style functions `mbrtoc8`, `mbrtoc16`, `mbrtoc32` and their inverses in `<cuchar>`, which convert between the locale's multibyte encoding and Unicode one code point at a time. For bulk conversion, write the loop yourself or use a library.

C++26 adds `std::text_encoding` in `<text_encoding>`, which is a C++26 feature. It does not convert anything. It identifies an encoding by its IANA registry number and name. `std::text_encoding::literal()` reports the ordinary literal encoding, and `std::text_encoding::environment()` reports the encoding the program's environment currently uses. The point is to let a program check before it assumes UTF-8.

```cpp
#include <text_encoding>

// C++26 only
static_assert(std::text_encoding::literal() == std::text_encoding::UTF8);
// Fails to compile if built with, for example, -fexec-charset=ISO-8859-1.
```

## What to remember

- A character type holds one code unit; text is a sequence of them in some encoding.
- `char`, `signed char` and `unsigned char` are three distinct types, and the signedness of `char` is implementation-defined.
- `wchar_t` has no portable encoding; `char8_t`, `char16_t` and `char32_t` are for UTF-8, UTF-16 and UTF-32.
- Since C++20, `u8` literals are `char8_t` arrays, which breaks conversion to `const char*` and stream output.
- A character literal must be encodable in one code unit; `u'\U0001F600'` is ill-formed.
- The ordinary literal encoding is chosen by the compiler, not by your source file; C++23 requires UTF-8 source support and adds named and delimited escapes.
- Pass `unsigned char` or `EOF` to `<cctype>` functions; a negative `char` is undefined.
- `size()` counts code units, so one displayed character can be one, two or more units, and canonically equal strings can compare unequal.
- `std::format` estimates width in columns, which is why precision can truncate to nothing.
- `<codecvt>` is deprecated and removed in C++26; `std::text_encoding` identifies encodings and is a C++26 feature.

## Concept Map Outline

- **Character types and Unicode:** A character type holds one code unit; what a reader sees as a character may span several.
  - **Character types:** Six types hold code units; only some have a portable encoding.
    - **char, signed, unsigned:** Three distinct types; the signedness of plain char is implementation-defined.
    - **wchar_t:** Size and encoding are implementation-defined, 16 bits on Windows and usually 32 elsewhere.
    - **char8_t, char16_t, char32_t:** Distinct types for UTF-8, UTF-16 and UTF-32 code units; char8_t arrived in C++20.
  - **Literals and encodings:** A prefix chooses the element type and the encoding of a literal.
    - **Prefixes u8, u, U, L:** u8 is UTF-8, u is UTF-16, U is UTF-32, and L uses the wide literal encoding.
    - **Ordinary literal encoding:** Chosen by the compiler, for example GCC's -fexec-charset, independent of the source file.
    - **Source encoding, C++23:** Implementations must support UTF-8 source files; the translation character set is Unicode.
    - **Char literal: one unit:** u'\U0001F600' is ill-formed in C++23 because the code point needs two UTF-16 units.
  - **Escapes:** Escapes name code points or raw code units without depending on the source encoding.
    - **Universal character names:** \u and \U name a code point and are encoded per the literal's encoding.
    - **Named and delimited, C++23:** \N{NAME}, \u{...}, \x{...} and \o{...} have no digit-count limit.
    - **\x versus \u:** \x writes a raw code unit value; \u names a code point.
  - **The char8_t break:** In C++20, u8 literals changed type and old code stopped compiling.
    - **Pointer conversion:** const char8_t* does not convert to const char*, so assigning a u8 literal to const char* fails.
    - **Stream output:** operator<< for char8_t and const char8_t* on narrow streams is deleted.
    - **Migration:** Use u8string, cast deliberately, or use an ordinary literal when it is UTF-8.
  - **Library limits:** The library counts code units and classifies single bytes; Unicode logic is yours.
    - **cctype negative char:** Arguments must fit unsigned char or equal EOF, so cast a plain char before calling.
    - **Code units versus graphemes:** size() counts code units; e plus a combining accent is three UTF-8 units but one grapheme.
    - **format width:** std::format estimates column width and truncates precision by whole grapheme clusters.
    - **No normalization:** The standard library has no normalization, collation or grapheme segmentation.
  - **Conversion and detection:** The old converters are on their way out; C++26 adds a way to identify encodings.
    - **codecvt deprecated:** Deprecated in C++17 and listed for removal in C++26; libstdc++ still ships it.
    - **cuchar functions:** mbrtoc8, mbrtoc16 and mbrtoc32 convert between the locale encoding and Unicode one code point at a time.
    - **text_encoding (C++26):** Identifies an encoding by IANA name and id; literal() reports the ordinary literal encoding.

## Standardese Quiz Questions

### Question 1 [warmup] ([lex.string], [basic.fundamental])

In C++20, what is the status of this program?

```cpp
const char* p = u8"abc";

int main() { return 0; }
```

A. Well-formed: a UTF-8 literal is an array of `const char`
B. Ill-formed: `const char8_t*` does not convert to `const char*`
C. Well-formed, but the literal is converted to the ordinary literal encoding
D. Undefined behavior at the conversion

**Answer (B):** Ill-formed: `const char8_t*` does not convert to `const char*`

**Why:** Since C++20 a `u8` string literal is an array of `const char8_t`, and `char8_t` is a distinct type, so there is no implicit conversion to `const char*`. In C++17 the literal was an array of `const char`, which is why this code used to compile and why the first option feels right. The diagnosis is a compile-time error, not a run-time problem.

### Question 2 [warmup] ([lex.string], [lex.charset])

In C++17 or later, what is printed? The arrays include the terminating null, which the code subtracts.

```cpp
#include <cstdio>
#include <iterator>

int main() {
  std::printf("%zu %zu %zu\n", std::size(u8"\u00e9") - 1,
              std::size(u"\U0001F600") - 1, std::size(U"\U0001F600") - 1);
}
```

A. 2 2 1
B. 2 1 1
C. 1 1 1
D. 2 2 2

**Answer (A):** 2 2 1

**Why:** `u8"\u00e9"` is encoded as UTF-8, where U+00E9 takes two code units. `u"\U0001F600"` is UTF-16, where a code point above U+FFFF becomes a surrogate pair of two code units, and `U"\U0001F600"` is UTF-32, where it is one unit. The option `1 1 1` counts code points, not the code units the arrays hold.

### Question 3 [warmup] ([lex.string])

In C++20, what is the status of this program?

```cpp
#include <iostream>

int main() {
  std::cout << u8"abc";
}
```

A. Well-formed: it prints `abc`
B. Well-formed: it prints a pointer value
C. Ill-formed: the stream insertion for `const char8_t*` is deleted
D. Undefined behavior: the stream reads past the array

**Answer (C):** Ill-formed: the stream insertion for `const char8_t*` is deleted

**Why:** C++20 added deleted overloads of `operator<<` for `char8_t` and `const char8_t*` on narrow streams, specifically to stop `u8` literals from printing as a pointer or as numbers. Overload resolution selects the deleted function, which makes the program ill-formed. In C++17 the same line compiled and printed `abc`, because the literal was `const char`.

### Question 4 [tricky] ([lex.string], [basic.fundamental])

In C++20 or later, what is printed?

```cpp
#include <cstdio>
#include <string>

int main() {
  std::u8string s = u8"e\u0301";
  std::printf("%zu\n", s.size());
}
```

A. 1
B. 2
C. 4
D. 3

**Answer (D):** 3

**Why:** `size()` counts code units. The letter `e` is one UTF-8 code unit and U+0301, the combining acute accent, is two, so the total is 3. It is also two code points and one grapheme cluster, which is why neither `1` nor `2` is a code-unit count.

### Question 5 [tricky] ([basic.fundamental])

What is printed on every conforming implementation?

```cpp
#include <cstdio>
#include <type_traits>

int main() {
  std::printf("%d\n", std::is_same_v<char, signed char> +
                       std::is_same_v<char, unsigned char>);
}
```

A. 1
B. 2
C. 0
D. It depends on whether `char` is signed

**Answer (C):** 0

**Why:** `char`, `signed char` and `unsigned char` are three distinct types in every implementation. Plain `char` behaves like one of the other two, and which one is implementation-defined, but it is never the same type as either. The tempting answer `1` confuses the representation with the type, and the last option is wrong because the result does not change with signedness.

### Question 6 [tricky] ([lex.ccon])

In C++23, what is the status of this declaration?

```cpp
char16_t c = u'\U0001F600';

int main() { return 0; }
```

A. Well-formed: it holds the high surrogate
B. Ill-formed: the code point is not encodable in a single `char16_t`
C. Well-formed: the value is truncated to 16 bits
D. Implementation-defined value

**Answer (B):** Ill-formed: the code point is not encodable in a single `char16_t`

**Why:** A character literal holds a single code unit. U+1F600 needs two UTF-16 code units, so it cannot be represented by a `char16_t` character literal, and C++23 makes such a literal ill-formed. Both compilers reject it, and neither truncates silently. `U'\U0001F600'` would be fine, since `char32_t` holds the whole code point.

### Question 7 [standardese] ([basic.fundamental])

Assume `char` is signed, `'\xE9'` converts to -23, and `EOF` is -1. Which function has undefined behavior when called as shown?

```cpp
#include <cctype>
#include <cstdio>

bool a(char c) { return std::isalpha(c); }
bool b(char c) { return std::isalpha(static_cast<unsigned char>(c)); }
bool c() { return std::isalpha(EOF); }

int main() { return b('\xE9') + c(); }
```

A. `a`, because `-23` is not representable as `unsigned char` and is not `EOF`
B. `b`, because the cast to `unsigned char` can overflow
C. `c`, because `EOF` is not a valid argument
D. None: `std::isalpha` accepts any `int`

**Answer (A):** `a`, because `-23` is not representable as `unsigned char` and is not `EOF`

**Why:** The `<cctype>` functions require an argument representable as `unsigned char` or equal to `EOF`; anything else is undefined. In `a`, a plain `char` with a negative value is passed unchanged, which breaks that rule. In `b` the cast yields 233, which is valid, and `c` passes `EOF`, which is explicitly allowed. The last option mistakes the `int` parameter type for the actual domain.

### Question 8 [standardese] ([depr.locale.stdcvt], [depr.conversions])

A C++23 program uses `std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t>` to convert UTF-32 to UTF-8. What does the C++23 standard say?

```cpp
#include <codecvt>
#include <locale>
#include <string>

int main() {
  std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> conv;
  std::string s = conv.to_bytes(U"abc");
  return s.size() == 3 ? 0 : 1;
}
```

A. Ill-formed: both were removed in C++20
B. The program is valid, and this is the recommended way to convert UTF encodings
C. The behavior is undefined because `codecvt_utf8` only supports UCS-2
D. The program is valid, and both facilities are deprecated, so a compiler may warn

**Answer (D):** The program is valid, and both facilities are deprecated, so a compiler may warn

**Why:** `<codecvt>` and `std::wstring_convert` were deprecated in C++17 and remain in the C++23 library, so using them is valid and typically produces a deprecation warning. They are listed for removal in C++26. The deprecation is the reason not to call them recommended, and the `char32_t` instantiation is supported, so it is not undefined.

# Integer arithmetic and overflow

> Unsigned integers wrap around, signed integers do not get to overflow at all, and promotion quietly turns narrow unsigned arithmetic into signed arithmetic. This topic covers the division rules, safe comparison, narrowing, and the newer saturating and checked operations.

- **Source:** C++ Atlas (https://cppatlas.com/topics/integer-arithmetic-and-overflow)
- **Track:** Library utilities
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [expr.pre] (https://eel.is/c++draft/expr.pre), [expr.mul] (https://eel.is/c++draft/expr.mul), [expr.const] (https://eel.is/c++draft/expr.const), [basic.fundamental] (https://eel.is/c++draft/basic.fundamental), [conv.integral] (https://eel.is/c++draft/conv.integral), [dcl.init.list] (https://eel.is/c++draft/dcl.init.list), [utility.intcmp] (https://eel.is/c++draft/utility.intcmp), [c.math.abs] (https://eel.is/c++draft/c.math.abs), [iterator.range] (https://eel.is/c++draft/iterator.range)
- **cppreference links:** [Arithmetic operators](https://en.cppreference.com/w/cpp/language/operator_arithmetic), [Integer comparison functions (cmp_less, in_range)](https://en.cppreference.com/w/cpp/utility/intcmp), [std::in_range](https://en.cppreference.com/w/cpp/utility/in_range), [Implicit conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion), [Usual arithmetic conversions](https://en.cppreference.com/w/cpp/language/usual_arithmetic_conversions), [Saturation arithmetic](https://en.cppreference.com/w/cpp/numeric/add_sat), [Undefined behavior](https://en.cppreference.com/w/cpp/language/ub), [Fixed width integer types](https://en.cppreference.com/w/cpp/types/integer)
- **Prerequisites:** fundamental-types-and-arithmetic-conversions, implicit-conversions, constant-expressions

## The one idea

C++ has two integer worlds with opposite contracts. Unsigned arithmetic is arithmetic modulo a power of two, so overflow is a defined, wrapping result. Signed arithmetic has no such result: if the mathematical value does not fit, the behaviour of the expression is undefined. The language does not wrap signed values even though C++20 requires two's complement representation.

> **Mental model.** An unsigned operation always has an answer, and that answer is reduced modulo 2 to the width. A signed operation has an answer only when the true result fits. When it does not, the program has left the rules, and the optimizer is allowed to have assumed that it never would.

The practical consequence is that a rule you learned for `unsigned` is a bug when you apply it to `int`, and the reverse. The part that surprises experienced programmers is how often an expression that looks unsigned is really signed, because of promotion.

## Signed overflow is undefined, and the compiler uses that

[expr.pre] says that if evaluating an expression produces a result that is not in the range of representable values for its type, the behaviour is undefined. For signed integers this is not a theoretical remark. Compilers use it to reason that `x + 1 > x` is always true.

```cpp
bool f(int x)      { return x + 1 > x; }  // GCC at -O2 on arm64 compiles this to "return true"
bool g(unsigned x) { return x + 1 > x; }  // false when x is UINT_MAX, and the code must handle it
```

You can ask the toolchain for help: `-fsanitize=signed-integer-overflow` reports the problem at run time, `-ftrapv` turns it into a trap, and `-fwrapv` gives it a wrapping meaning as a non-standard extension. Constant evaluation is the standard's own detector. A `constexpr` initializer whose evaluation overflows is not a constant expression, so the compiler must reject it.

```cpp
#include <climits>

// constexpr int a = INT_MAX + 1;   // ill-formed: signed overflow is not a constant expression
constexpr unsigned b = UINT_MAX + 1u;  // OK: unsigned arithmetic wraps, b is 0
static_assert(b == 0);
```

The consequence for checks is that you must test before the operation, never after it. Writing `if (a + b < a)` to detect overflow of a signed `a + b` is itself undefined when it overflows, and the optimizer is free to delete the test because it may assume the sum never wraps. The portable form compares against the limits first.

```cpp
#include <climits>

bool add_overflows(int a, int b) {
  return (b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b);
}
// Wrong: return a + b < a;   // evaluates the overflowing addition, then tests it
```

For unsigned values the after-the-fact test is fine, because wrapping is defined: `a + b < a` is true exactly when the unsigned sum wrapped. That asymmetry is another reason to keep sizes and bit patterns unsigned and to keep quantities that can go negative signed.

## Promotion turns unsigned into signed

Operands narrower than `int` are promoted before arithmetic. On a platform with 32-bit `int`, an `unsigned short` becomes an `int`, so multiplying two of them is a signed multiplication that can overflow. The rules for promotion and the usual arithmetic conversions are in `fundamental-types-and-arithmetic-conversions`. Here the consequence matters.

```cpp
constexpr unsigned short a = 65535;
// constexpr auto r = a * a;
// ill-formed with 32-bit int: both promote to int, and 4294836225 does not fit
constexpr auto ok = static_cast<unsigned>(a) * a;  // OK: 4294836225u, unsigned arithmetic
```

The type of `r` would be `int`, not `unsigned short` or `unsigned`. The same trap catches `uint8_t` and `uint16_t` arithmetic in hash functions and checksums. The fix is to convert one operand to `unsigned` before the operation. Writing `1u * a * b` does the same.

## Division and remainder

Division truncates toward zero. This has been required since C++11, where earlier standards left it to the implementation for negative operands. The remainder has the sign of the dividend, and the identity `(a / b) * b + a % b == a` always holds when the quotient is representable.

```cpp
#include <cstdio>

int main() {
  std::printf("%d %d\n", -7 / 2, -7 % 2);   // -3 -1
  std::printf("%d %d\n", 7 / -2, 7 % -2);   // -3 1
}
```

Dividing by zero is undefined for both `/` and `%`. The other case is `INT_MIN / -1`, whose mathematical result 2147483648 does not fit in a 32-bit `int`. [expr.mul] says that when the quotient is not representable, the behaviour of both `a / b` and `a % b` is undefined. So `INT_MIN % -1` is undefined as well, although its mathematical value would be 0. On x86 the hardware traps on it.

> **Standardese.** [expr.mul] states that for integral operands, if the quotient `a / b` is representable in the type of the result, then `(a / b) * b + a % b` equals `a`; otherwise the behaviour of both `a / b` and `a % b` is undefined. This is why the remainder operator shares the hazard of the division.

`std::abs(INT_MIN)` fails the same way: the absolute value is not representable, and [c.math.abs] leaves it undefined. If you need the absolute value of an arbitrary `int`, compute in a wider type or convert to `unsigned` first.

## Comparing mixed signs safely

When a signed and an unsigned operand of the same rank meet, the signed one is converted to unsigned. So `-1 < 1u` is false, because `-1` becomes `UINT_MAX`. The surprise disappears when the unsigned type is narrower: `-1 < static_cast<unsigned short>(1)` is true, because both promote to `int`.

C++20 added comparison functions in `<utility>` that compare by mathematical value. They are `std::cmp_equal`, `cmp_not_equal`, `cmp_less`, `cmp_greater`, `cmp_less_equal` and `cmp_greater_equal`. Next to them is `std::in_range<R>(value)`, which tells you whether a value fits in type `R`.

```cpp
#include <cstdint>
#include <cstdio>
#include <utility>

int main() {
  std::printf("%d %d\n", -1 < 1u, std::cmp_less(-1, 1u));  // 0 1
  std::printf("%d %d\n", std::in_range<unsigned>(-1),
                         std::in_range<std::uint8_t>(255)); // 0 1
}
```

These functions accept only standard and extended integer types. `char`, `bool`, `char8_t`, `char16_t`, `char32_t` and `wchar_t` are rejected at compile time, so `std::cmp_less('a', 1)` is ill-formed. The functions are meant for numbers only.

C++20 also added `std::ssize(c)`, which returns a signed size, so loops over indices need no cast. Together with the previous point, this is the standard cure for the classic loop bug.

```cpp
#include <vector>

void bad(const std::vector<int>& v) {
  // for (std::size_t i = v.size() - 1; i >= 0; --i)  // i >= 0 is always true; v.size() - 1 wraps if empty
}

void good(const std::vector<int>& v) {
  for (auto i = std::ssize(v) - 1; i >= 0; --i) { (void)v[i]; }
  for (auto i = v.size(); i-- > 0; ) { (void)v[i]; }  // unsigned idiom, correct for empty vectors
}
```

> **Pitfall.** An empty vector has `size()` equal to zero, and `size() - 1` is `SIZE_MAX`, a well-defined wrap that is almost never what you meant. The condition `i >= 0` on an unsigned `i` is always true, so the first loop above never ends on its own.

## Narrowing and conversion

Converting any integer to an unsigned type is always modular. Converting to a signed type, when the value does not fit, was implementation-defined until C++20, and since C++20 it is modular too: the result is the unique value congruent to the source modulo 2 to the width. So an `int` holding 200 converts to `std::int8_t` as -56 in every C++20 program.

```cpp
#include <cstdint>

void narrow(int big) {
  std::int8_t a = big;      // if big is 200: -56 since C++20, implementation-defined before
  unsigned u = -1;          // UINT_MAX, always
  // std::int8_t b{big};    // ill-formed: narrowing in list-initialization
  std::int8_t c{100};       // OK: a constant that fits is not narrowing
  (void)a; (void)u; (void)c;
}
```

List-initialization is stricter. A conversion that may change the value is ill-formed unless the source is a constant expression whose value fits. Defined does not mean harmless: a modular conversion still silently changes the number.

## Saturating and checked arithmetic

Two library features give you overflow handling without undefined behaviour. Both are C++26.

Saturating arithmetic in `<numeric>` clamps to the limits of the type. The C++26 draft names the functions `std::add_sat`, `std::sub_sat`, `std::mul_sat` and `std::div_sat`, plus `std::saturate_cast<R>(x)`. These are C++26 additions. The libstdc++ 16 headers used for this topic spell the same operations `saturating_add`, `saturating_sub`, `saturating_mul`, `saturating_div` and `saturating_cast`, so check your library before relying on the draft names.

```cpp
// C++26: std::add_sat(std::int8_t{100}, std::int8_t{100}) == 127
// C++26: std::saturate_cast<std::uint8_t>(-5) == 0
```

Checked arithmetic comes from the C23 header `<stdckdint.h>`, which C++26 adopts. The functions `ckd_add`, `ckd_sub` and `ckd_mul` take a pointer to the result and two integer operands. They return `true` if the result did not fit, and in that case they store the wrapped value.

```cpp
#include <stdckdint.h>  // C++26

int r;
bool overflowed = ckd_add(&r, 2147483647, 1);  // true, and r holds the wrapped result
```

Until your toolchain has them, the compiler builtins `__builtin_add_overflow` and its relatives do the same job in GCC and Clang.

## What to remember

- Unsigned overflow wraps modulo 2 to the width; signed overflow is undefined, and compilers optimize on that.
- Constant evaluation rejects signed overflow, which makes `constexpr` a good test for it.
- `unsigned short * unsigned short` is a signed `int` multiplication; convert an operand to `unsigned` first.
- Division truncates toward zero since C++11, and the remainder takes the sign of the dividend.
- `INT_MIN / -1` and `INT_MIN % -1` are both undefined, as is division by zero and `std::abs(INT_MIN)`.
- `-1 < 1u` is false; use `std::cmp_less` and friends, or `std::in_range`, to compare by value.
- The `cmp_*` functions reject `char` types and `bool`.
- Use `std::ssize` or the `i-- > 0` idiom to avoid `size_t` underflow in loops.
- Narrowing to a signed type is modular since C++20, but list-initialization still forbids narrowing.
- C++26 adds saturating operations in `<numeric>` and checked `ckd_*` operations in `<stdckdint.h>`.

## Concept Map Outline

- **Integer arithmetic and overflow:** Unsigned wraps by definition; signed overflow is undefined; promotion hides which one you are doing.
  - **Overflow contracts:** Unsigned arithmetic is modular; signed overflow leaves the language rules.
    - **Unsigned wraparound:** Results are reduced modulo 2 to the width, so UINT_MAX + 1u is 0.
    - **Signed overflow:** Undefined behavior under [expr.pre]; compilers may assume it never happens.
    - **Two's complement, C++20:** The representation is now fixed, but signed overflow is still undefined.
    - **Constant evaluation:** Overflow in a constexpr initializer is not a constant expression, so it is diagnosed.
  - **Promotion trap:** Narrow unsigned operands become int before arithmetic.
    - **unsigned short product:** Both operands promote to int, so 65535 * 65535 overflows with a 32-bit int.
    - **The fix:** Cast an operand to unsigned first, or write 1u * a * b.
  - **Division and remainder:** Quotients truncate toward zero and the remainder follows the dividend.
    - **Truncation, C++11:** -7 / 2 is -3 and -7 % 2 is -1; (a / b) * b + a % b equals a.
    - **INT_MIN / -1:** The quotient does not fit, so both division and remainder are undefined.
    - **Division by zero:** Undefined for both / and %.
    - **abs(INT_MIN):** The result is not representable, so the behavior is undefined.
  - **Comparing integers:** Mixed-sign comparison converts to unsigned; C++20 adds value-based helpers.
    - **-1 < 1u is false:** The signed operand converts to unsigned, so -1 becomes UINT_MAX.
    - **cmp_less family:** std::cmp_* compare mathematical values; they reject char types and bool.
    - **in_range:** std::in_range<R>(v) tells whether v fits in type R without converting it.
    - **ssize and loops:** Use std::ssize or i-- > 0 to avoid size_t underflow in reverse loops.
  - **Conversions:** Conversion to unsigned is modular; to signed it is modular since C++20.
    - **Narrowing to signed:** 200 to int8_t is -56 in C++20; it was implementation-defined before.
    - **List-initialization:** Narrowing is ill-formed unless the source is a constant that fits.
  - **Safe arithmetic, C++26:** Library tools that handle overflow without undefined behavior.
    - **Saturating operations:** C++26 clamps to the type's limits; libstdc++ 16 spells them saturating_add and so on.
    - **ckd_add and ckd_mul:** From <stdckdint.h>: return true on overflow and store the wrapped result.
    - **Compiler builtins:** __builtin_add_overflow does the same job in GCC and Clang today.

## Standardese Quiz Questions

### Question 1 [warmup] ([utility.intcmp], [expr.rel])

In C++20 or later, what is printed?

```cpp
#include <cstdio>
#include <utility>

int main() {
  std::printf("%d %d\n", -1 < 1u, std::cmp_less(-1, 1u));
}
```

A. 1 1
B. 0 1
C. 1 0
D. 0 0

**Answer (B):** 0 1

**Why:** In `-1 < 1u` the signed operand is converted to `unsigned int`, so `-1` becomes `UINT_MAX` and the comparison is false. `std::cmp_less` compares the mathematical values, so it reports that -1 is less than 1. The option `1 1` assumes the built-in comparison behaves like `cmp_less`, which is the usual surprise.

### Question 2 [warmup] ([expr.mul])

In C++11 or later, what is printed?

```cpp
#include <cstdio>

int main() {
  std::printf("%d %d %d %d\n", -7 / 2, -7 % 2, 7 / -2, 7 % -2);
}
```

A. -3 -1 -3 1
B. -4 1 -4 1
C. -3 1 -3 -1
D. -4 -1 -3 1

**Answer (A):** -3 -1 -3 1

**Why:** Division truncates toward zero, so `-7 / 2` and `7 / -2` are both -3. The remainder takes the sign of the dividend, which makes `-7 % 2` equal to -1 and `7 % -2` equal to 1, so that `(a / b) * b + a % b == a` holds. Rounding toward negative infinity, as in the option with -4, is what `>>` does, not `/`.

### Question 3 [warmup] ([basic.fundamental], [expr.pre])

What is printed? `std::size_t` is an unsigned type.

```cpp
#include <cstddef>
#include <cstdio>

int main() {
  std::size_t n = 0;
  std::printf("%d\n", n - 1 > 5);
}
```

A. 0
B. Undefined behavior: the subtraction underflows
C. Ill-formed: a negative value cannot be `std::size_t`
D. 1

**Answer (D):** 1

**Why:** Unsigned arithmetic is modular, so `n - 1` with `n == 0` is `SIZE_MAX`, which is greater than 5, and the program prints 1. There is no undefined behavior here, because unsigned wraparound is defined. The wrapped value is the reason loops of the form `i >= 0` on an unsigned `i` never terminate.

### Question 4 [tricky] ([conv.prom], [expr.pre], [expr.const])

Assume `int` is 32 bits. What is the status of this program?

```cpp
constexpr unsigned short a = 65535;
constexpr auto r = a * a;

int main() { return 0; }
```

A. Ill-formed: the multiplication overflows `int`, so it is not a constant expression
B. Well-formed: unsigned arithmetic wraps, so `r` is 4294836225
C. Well-formed: the product is -131071
D. Ill-formed: narrowing conversion

**Answer (A):** Ill-formed: the multiplication overflows `int`, so it is not a constant expression

**Why:** Both operands are promoted to `int` before the multiplication, so this is a signed multiplication, and 65535 times 65535 is 4294836225, which does not fit in a 32-bit `int`. Signed overflow is undefined, and undefined behavior is not allowed in a constant expression, so the initializer is rejected. Wraparound would only happen if an operand were first converted to `unsigned`.

### Question 5 [tricky] ([expr.mul], [expr.const])

Assume `int` is 32 bits two's complement. What is the status of this declaration?

```cpp
#include <climits>

constexpr int b = INT_MIN % -1;

int main() { return 0; }
```

A. Well-formed: `b` is 0, since the remainder is mathematically 0
B. Well-formed: `b` is `INT_MIN`
C. Ill-formed: the initializer is not a constant expression
D. Well-formed with an unspecified value

**Answer (C):** Ill-formed: the initializer is not a constant expression

**Why:** The quotient `INT_MIN / -1` is 2147483648, which is not representable in `int`. [expr.mul] says that in that case the behavior of both `a / b` and `a % b` is undefined, so the remainder shares the problem, and undefined behavior is not a constant expression. The mathematical value 0 is the tempting answer, but the standard does not give `%` a separate rule.

### Question 6 [tricky] ([conv.integral])

In C++20, assuming `std::int8_t` is an 8-bit two's complement type, what is printed?

```cpp
#include <cstdint>
#include <cstdio>

int main() {
  int big = 200;
  std::int8_t x = big;
  std::printf("%d\n", x);
}
```

A. 200
B. -56
C. 127
D. Undefined behavior

**Answer (B):** -56

**Why:** Since C++20, converting an integer that does not fit to a signed type is modular: 200 is congruent to -56 modulo 256 in the range of an 8-bit signed type. Before C++20 the result was implementation-defined, but it was never undefined. The option 127 describes saturation, which the language does not do.

### Question 7 [standardese] ([utility.intcmp], [basic.fundamental])

In C++20, what is the status of this program?

```cpp
#include <utility>

int main() {
  return std::cmp_less('a', 1) + std::cmp_less(true, 1);
}
```

A. Well-formed: it returns 1
B. Well-formed: `char` is compared as if signed
C. Well-formed, but `bool` is converted to `int` first
D. Ill-formed: `char` and `bool` are not standard or extended integer types

**Answer (D):** Ill-formed: `char` and `bool` are not standard or extended integer types

**Why:** The `std::cmp_*` functions and `std::in_range` require both operands to be standard or extended integer types. Neither `char` nor `bool` is one, so the call is ill-formed. Compilers diagnose it with a static assertion or a failed constraint rather than converting the arguments.

### Question 8 [standardese] ([c.math.abs], [expr.pre])

For a 32-bit two's complement `int`, what does the standard say about `std::abs(INT_MIN)`?

A. It has undefined behavior, because the absolute value is not representable in `int`
B. It returns `INT_MIN`, because the value wraps
C. It returns `INT_MAX`, because the result saturates
D. It returns 2147483648 as an `unsigned int`

**Answer (A):** It has undefined behavior, because the absolute value is not representable in `int`

**Why:** The integer overloads of `std::abs` return an `int` and leave the case where the result is not representable undefined, as the C function does. Wrapping to `INT_MIN` is what many implementations happen to do, which makes it tempting, but the standard does not promise it. The result type never changes to `unsigned`.

---

# Track: C++26

Contracts, static reflection, structured concurrency with std::execution and erroneous behavior.

# C++26: Contracts, Reflection, Execution, and Erroneous Behavior

> How C++26 replaces fragile workarounds with language-level contracts (P2900), value-based static reflection (P2996), std::execution senders (P2300), and erroneous behavior (P2795).

- **Source:** C++ Atlas (https://cppatlas.com/topics/cpp26-contracts-reflection-execution)
- **Track:** C++26
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [basic.contract] (https://eel.is/c++draft/basic.contract), [expr.reflect] (https://eel.is/c++draft/expr.reflect), [meta.reflection] (https://eel.is/c++draft/meta.reflection), [exec] (https://eel.is/c++draft/exec), [basic.indet] (https://eel.is/c++draft/basic.indet)
- **cppreference links:** [Contract assertions](https://en.cppreference.com/w/cpp/language/contracts), [Function contract specifiers](https://en.cppreference.com/w/cpp/language/functions/function_contract_specifiers), [Reflection operator](https://en.cppreference.com/w/cpp/language/operator_reflection), [Reflection library](https://en.cppreference.com/w/cpp/meta/reflection), [Execution control library](https://en.cppreference.com/w/cpp/execution), [attribute: indeterminate](https://en.cppreference.com/w/cpp/language/attributes/indeterminate)
- **Prerequisites:** sfinae-and-concepts, atomics-and-memory-ordering

C++26 closes four longstanding structural gaps in the language: executable function contracts (**P2900**), value-based static reflection (**P2996**), structured asynchronous execution (**P2300**), and eliminating time-travel undefined behavior from uninitialized automatic locals (**P2795**).

> **Mental model.** Each C++26 pillar moves an informal convention into checked language or library machinery: comments become `pre`/`post` contracts, macro boilerplate becomes `consteval` `std::meta::info` values, ad-hoc callbacks become lazy sender graphs, and uninitialized stack reads become bounded erroneous behavior.

## Contracts (P2900): pre, post, and contract_assert

P2900 introduces two contextual function contract specifiers—`pre(...)` and `post(result: ...)`—plus the statement keyword `contract_assert(...)`. Unlike `assert()` macros that vanish completely under `NDEBUG`, C++26 contract assertions remain valid C++ syntax in every build and execute according to one of **four evaluation semantics** configured externally by the toolchain:

- **`ignore`:** predicate is checked semantically at compile time (so invalid code still fails to compile) but not evaluated at runtime.
- **`observe`:** evaluates the predicate; on violation, invokes the violation handler and continues execution.
- **`enforce`:** evaluates the predicate; on violation, invokes the handler and terminates (`std::terminate` or aborting).
- **`quick_enforce`:** evaluates the predicate; on violation, terminates immediately without invoking the user-replaceable handler.

Every expression inside a contract predicate undergoes **constification**: variables named inside `pre`, `post`, or `contract_assert` are viewed as `const` so predicates cannot silently mutate program state. Furthermore, any by-value parameter referenced in a `post` condition must be declared `const` on the function definition so caller and callee never disagree about pre-mutation vs post-mutation values. The snippet matches GCC 16 (`-std=c++26 -fcontracts`):

```cpp
#include <contracts>

int clamp_positive(const int value, const int max_val)
    pre(max_val > 0)
    post(r: r >= 0 && r <= max_val)
{
    contract_assert(max_val != 0);
    if (value < 0) return 0;
    return value > max_val ? max_val : value;
}
```

> **Pitfall.** Writing `int clamp(int value, int max_val) post(r: r <= max_val)` without `const` on `max_val` is ill-formed under P2900 `[dcl.contract.func]`. Because the function body could modify a non-`const` by-value parameter, C++26 requires any parameter named in a `post` specifier to be `const` (or accessed through a reference whose binding is fixed).

## Static Reflection (P2996): ^^, std::meta::info, and splicing

For decades, serializing a `struct` or printing `enum` names required macros, external code generators, or fragile structured-binding tricks. P2996 introduces **value-based reflection**: the unary reflection operator `^^` yields a `consteval`-only scalar value of opaque type `std::meta::info`.

Because every reflected entity—type, non-static data member, enumerator, function, or template—has the single type `std::meta::info`, compile-time code uses ordinary `<meta>` functions and ranges rather than recursive template specializations. Pair reflection with **splicing** (`[:refl:]`) to turn a `std::meta::info` back into an entity or member access, and **expansion statements** (`template for`, P1306) to iterate across compile-time ranges. The example verifies cleanly under GCC 16 (`-std=c++26 -freflection`):

```cpp
#include <cstddef>
#include <meta>

struct Metrics {
    int requests;
    double latency_ms;
    bool healthy;
};

template <typename T>
constexpr std::size_t sum_field_bytes() {
    std::size_t total = 0;
    template for (constexpr auto member : std::define_static_array(
        std::meta::nonstatic_data_members_of(
            ^^T, std::meta::access_context::current())))
    {
        total += std::meta::size_of(member);
    }
    return total;
}

static_assert(sum_field_bytes<Metrics>() == sizeof(int) + sizeof(double) + sizeof(bool));

template <std::size_t Index, typename T>
constexpr auto get_field(const T& obj) {
    constexpr auto members = std::define_static_array(
        std::meta::nonstatic_data_members_of(
            ^^T, std::meta::access_context::current()));
    return obj.[:members[Index]:];
}
```

Notice `std::meta::access_context::current()`: reflection respects C++ access control by default, querying members visible from the caller's lexical scope unless explicitly given `access_context::unchecked()`.

## Structured concurrency with std::execution (P2300)

P2300 standardizes a zero-overhead asynchronous model in `<execution>` built from three composable roles:

```text
Scheduler ──schedule()──▶ Sender (lazy graph) ──connect(sender, receiver)──▶ Operation State ──start()──▶ Receiver
                                                                                                         ├─ set_value(...)
                                                                                                         ├─ set_error(err)
                                                                                                         └─ set_stopped()
```

- **Schedulers** are lightweight handles to execution contexts (thread pools, event loops, GPU queues); calling `schedule(sched)` returns a sender representing work starting on that context.
- **Senders** describe asynchronous computations lazily without allocating or starting threads when built. Every sender completes on exactly one of three channels: value (`set_value`), error (`set_error`), or cooperative cancellation (`set_stopped`).
- **Receivers** handle those three completion signals. Calling `std::execution::connect(sender, receiver)` produces an immovable `operation_state` that embeds intermediate state inline; work runs only when `start(op)` executes.

Algorithms such as `then`, `let_value`, `when_all`, `bulk`, `on`, and `upon_error` compose pipelines declaratively, and `std::this_thread::sync_wait` blocks at the root edge to collect results. Because standard library vendors are actively staging P2300 implementations (GCC 16's `<execution>` currently ships C++17 parallel policies and not yet P2300 sender adaptors), the following example illustrates the standardized C++26 P2300R10 library syntax:

```cpp
// C++26 P2300R10 standard library syntax (<execution>)
#include <execution>
#include <thread>
#include <utility>

int run_pipeline(std::execution::scheduler auto sched) {
    namespace ex = std::execution;
    auto graph =
        ex::schedule(sched)
        | ex::then([] { return 21; })
        | ex::then([](int v) { return v * 2; });

    auto [answer] = std::this_thread::sync_wait(std::move(graph)).value();
    return answer;
}
```

> **Pitfall.** Constructing `ex::schedule(sched) | ex::then(work)` schedules nothing and allocates no work items on its own. Without connecting to a receiver and calling `start`, or passing the graph to a consumer such as `std::this_thread::sync_wait`, the pipeline remains an inert description.

## Erroneous Behavior (P2795) and [[indeterminate]]

Before C++26, reading an uninitialized automatic local scalar (`int x; return x;`) triggered **Undefined Behavior (UB)**. Under aggressive optimization, UB allowed compilers to assume the path was unreachable and delete downstream bounds checks or error handlers.

P2795 eliminates that hazard by introducing **Erroneous Behavior (EB)**: a bug category strictly weaker than UB. When an automatic variable without an initializer is read before being written, C++26 specifies that the object holds an implementation-determined **erroneous value** (typically zero-initialized or deterministic pattern-filled by the compiler). The program remains buggy and compilers or sanitizers are encouraged to diagnose it, yet runtime execution stays well-defined—preventing arbitrary time-travel miscompilations.

When a hot path genuinely needs raw uninitialized storage (for instance, a large stack scratch buffer overwritten piecemeal), annotate the declaration with `[[indeterminate]]`, verified in GCC 16 (`-std=c++26`):

```cpp
#include <cstddef>

int erroneous_read() {
    int count;    // C++26: initialized to an erroneous value; reading is EB, not UB
    return count;
}

std::byte fast_scratch() {
    [[indeterminate]] std::byte buffer[4096]; // Opts out: reading before write remains UB
    buffer[0] = std::byte{0x2A};
    return buffer[0];
}
```

> **Standardese.** Under C++26 `[basic.indet]`, automatic storage duration objects without `[[indeterminate]]` never have indeterminate values—reading them prior to assignment produces erroneous behavior rather than undefined behavior `[intro.abstract]`.

## Comparing the four C++26 additions

| Feature | Paper | Primary mechanism | Verification in GCC 16 |
| --- | --- | --- | --- |
| Contracts | P2900R14 | `pre`, `post`, `contract_assert`, four semantics | Compiles with `-std=c++26 -fcontracts` |
| Static Reflection | P2996 + P1306 | `^^`, `std::meta::info`, `[:r:]`, `template for` | Compiles with `-std=c++26 -freflection` |
| `std::execution` | P2300R10 | Senders, receivers, schedulers, `sync_wait` | P2300 library rollouts pending |
| Erroneous Behavior | P2795R5 | Bounded EB on uninitialized locals, `[[indeterminate]]` | `[[indeterminate]]` compiles with `-std=c++26` |

## What to remember

- P2900 contracts keep predicates constified, require `const` on value parameters named in `post`, and separate assertion syntax from build-time evaluation semantics (`ignore`, `observe`, `enforce`, `quick_enforce`).
- P2996 static reflection represents program entities as `consteval` `std::meta::info` values created with `^^`, inspected via `<meta>`, iterated with `template for`, and turned back into code with splices `[:r:]`.
- P2300 `std::execution` builds lazy async graphs over schedulers, senders, and three-channel receivers (`set_value`, `set_error`, `set_stopped`) without heap allocation until connected and started.
- P2795 turns reads of uninitialized automatic locals into well-defined erroneous behavior, reserving pre-C++26 indeterminate UB strictly for declarations marked `[[indeterminate]]`.

## Concept Map Outline

- **C++26 core additions:** Four C++26 pillars modernize safety, compile-time introspection, async concurrency, and uninitialized locals.
  - **Contracts (P2900):** Language-level pre, post, and contract_assert assertions with configurable runtime semantics.
    - **Four evaluation semantics:** Toolchains choose ignore, observe, enforce, or quick_enforce outside source code.
      - **Enforce vs quick_enforce:** Both terminate on failure, with quick_enforce skipping the violation handler.
    - **Constification rules:** Predicates view variables as const; postconditions require const value parameters.
    - **Violation handler:** contract_violation reports kind, semantic, mode, location, and terminating status.
  - **Static reflection (P2996):** Value-based compile-time introspection via ^^ and consteval std::meta::info.
    - **Reflection operator ^^:** Produces a consteval std::meta::info value for types, members, functions, or templates.
    - **Splicing and template for:** Splices [:r:] reify reflections while template for unrolls reflection ranges.
      - **std::define_static_array:** Converts compile-time reflection vectors into static arrays usable by template for.
    - **Access context:** access_context::current() enforces member visibility unless unchecked() is requested.
  - **std::execution (P2300):** Zero-allocation structured async pipelines built from senders, receivers, and schedulers.
    - **Three completion channels:** Every sender finishes with set_value, set_error, or cooperative set_stopped.
      - **Structured cancellation:** set_stopped propagates cancellation signals downstream without throwing exceptions.
    - **Connect and start:** Sender pipelines stay inert until connected into an operation state and started.
      - **std::this_thread::sync_wait:** Blocks the caller at the pipeline boundary until the sender completes.
  - **Erroneous behavior (P2795):** Eliminates time-travel UB from uninitialized automatic scalars while preserving opt-out.
    - **Deterministic erroneous value:** Reading an uninitialized local triggers well-defined erroneous behavior, not unbounded UB.
    - **[[indeterminate]] opt-out:** Explicitly marks hot-path scratch buffers to retain uninitialized storage semantics.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.contract])

Which four evaluation semantics are defined for P2900 contract assertions in C++26?

A. ignore, observe, enforce, and quick_enforce
B. debug, release, audit, and assume
C. off, warn, throw_on_fail, and abort
D. constexpr_only, runtime_check, log, and trap

**Answer (A):** ignore, observe, enforce, and quick_enforce

**Why:** P2900 defines four evaluation semantics: ignore (compile-checked, not evaluated at runtime), observe (evaluate and invoke handler, then continue), enforce (evaluate, invoke handler, then terminate), and quick_enforce (evaluate and terminate immediately without calling the handler).

### Question 2 [warmup] ([expr.reflect], [meta.reflection])

In P2996 static reflection, what is the type of the expression ^^MyStruct, and when can it exist?

```cpp
struct MyStruct { int x; };
constexpr auto r = ^^MyStruct;
```

A. std::type_info, usable at runtime
B. std::meta::info, a consteval-only scalar type usable strictly in constant evaluation
C. std::string_view containing "MyStruct"
D. std::tuple<int> describing its members

**Answer (B):** std::meta::info, a consteval-only scalar type usable strictly in constant evaluation

**Why:** The reflection operator ^^ yields a value of std::meta::info, which is a consteval-only type in [expr.reflect] and [meta.reflection]. It cannot persist as a runtime object or be stored outside constant evaluation.

### Question 3 [tricky] ([dcl.contract.func])

Why does GCC 16 (-std=c++26 -fcontracts) reject the following P2900 postcondition?

```cpp
int safe_div(int a, int b)
    pre(b != 0)
    post(r: r * b <= a)
{
    return a / b;
}
```

A. post cannot refer to two parameters in the same expression
B. a and b are integer types rather than references
C. Any non-reference parameter referenced inside a postcondition specifier must be declared const
D. post must appear before pre on the declaration

**Answer (C):** Any non-reference parameter referenced inside a postcondition specifier must be declared const

**Why:** Under P2900 [dcl.contract.func], if a postcondition names a by-value parameter of the function, that parameter must be const-qualified on the definition (e.g., const int a, const int b); otherwise the function could mutate its local copy and make the postcondition ambiguous.

### Question 4 [tricky] ([exec.snd], [exec.opstate])

In P2300 std::execution, what work runs when you evaluate only the pipeline expression auto s = std::execution::just(10) | std::execution::then(fn);?

```cpp
auto s = std::execution::just(10)
       | std::execution::then([](int x) { side_effect(); return x + 1; });
```

A. side_effect() runs eagerly on the calling thread
B. side_effect() is queued on the default system thread pool immediately
C. Nothing executes yet: senders are lazy descriptions that do not run until connected to a receiver and started (or consumed by std::this_thread::sync_wait)
D. Compilation fails because just() cannot precede then()

**Answer (C):** Nothing executes yet: senders are lazy descriptions that do not run until connected to a receiver and started (or consumed by std::this_thread::sync_wait)

**Why:** P2300 senders are lazy work descriptions. Constructing and piping senders builds a typed expression graph without starting execution or allocating work until connect(sender, receiver) produces an operation state and start(op) (or sync_wait) runs it.

### Question 5 [standardese] ([basic.indet], [intro.abstract])

Under C++26 P2795 (Erroneous Behavior), what happens at runtime when a program reads an uninitialized local int x; without [[indeterminate]]?

```cpp
int f() {
    int x;
    return x;
}
```

A. Unbounded undefined behavior, allowing compilers to eliminate surrounding checks
B. Ill-formed diagnostic required: the program fails to compile
C. Throws std::logic_error at runtime
D. Erroneous behavior: the program contains a bug, yet runtime execution is well-defined because x receives an implementation-determined erroneous value rather than causing UB

**Answer (D):** Erroneous behavior: the program contains a bug, yet runtime execution is well-defined because x receives an implementation-determined erroneous value rather than causing UB

**Why:** P2795 [basic.indet] classifies reading an uninitialized automatic variable (not marked [[indeterminate]]) as erroneous behavior rather than undefined behavior. Implementations initialize it to an erroneous value (such as zero or a fixed pattern), eliminating UB time-travel optimizations.

### Question 6 [standardese] ([exec.recv], [exec.set.value])

What are the exact three completion channels a P2300 receiver handles in std::execution?

A. set_value, set_error, and set_stopped
B. on_next, on_error, and on_complete
C. resolve, reject, and finally
D. return_value, throw_exception, and cancel_token

**Answer (A):** set_value, set_error, and set_stopped

**Why:** In [exec.recv], every P2300 sender completes by invoking exactly one of three receiver customization points: set_value(rcvr, args...), set_error(rcvr, err), or set_stopped(rcvr) (representing cooperative cancellation).

# Contracts

> C++26 adds preconditions, postconditions and contract_assert. A contract assertion is a redundant check whose evaluation semantic, from ignore to quick-enforce, is chosen by the implementation rather than written in the code.

- **Source:** C++ Atlas (https://cppatlas.com/topics/contracts)
- **Track:** C++26
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [basic.contract.general] (https://eel.is/c++draft/basic.contract.general), [basic.contract.eval] (https://eel.is/c++draft/basic.contract.eval), [basic.contract.handler] (https://eel.is/c++draft/basic.contract.handler), [dcl.contract.func] (https://eel.is/c++draft/dcl.contract.func), [dcl.contract.res] (https://eel.is/c++draft/dcl.contract.res), [stmt.contract.assert] (https://eel.is/c++draft/stmt.contract.assert), [expr.prim.id.unqual] (https://eel.is/c++draft/expr.prim.id.unqual), [expr.call] (https://eel.is/c++draft/expr.call), [support.contract] (https://eel.is/c++draft/support.contract), [structure.specifications] (https://eel.is/c++draft/structure.specifications)
- **cppreference links:** [Contract assertions](https://en.cppreference.com/w/cpp/language/contracts), [Function contract specifiers](https://en.cppreference.com/w/cpp/language/function), [contract_assert statement](https://en.cppreference.com/w/cpp/language/contract_assert), [Standard library header <contracts>](https://en.cppreference.com/w/cpp/header/contracts), [std::contracts::contract_violation](https://en.cppreference.com/w/cpp/contract/contract_violation), [assert](https://en.cppreference.com/w/cpp/error/assert), [C++ attribute: assume](https://en.cppreference.com/w/cpp/language/attributes/assume)

## The one idea

A contract assertion states something that a correct program already guarantees. It is a redundant check, not logic. The code says *what* should be true; how that check behaves, whether it is skipped, logged, or fatal, is decided by the implementation, usually through a build flag, and can even differ from one evaluation to the next.

This is C++26, specified by P2900R14 and adopted into the working draft in February 2025. Everything here follows N5050, the final C++26 draft that went to the international ballot. That ballot closed in October 2026 and was reported as not approved, with contracts at the centre of the dispute, so check the status before you quote it as published ISO C++. Compiler support is experimental: GCC 16 needs `-std=c++26 -fcontracts`, and it differs from the draft in a few places noted below.

> **Mental model.** Write each predicate so that deleting it, checking it, or checking it twice would leave a correct program unchanged. Every rule in this feature follows from protecting that property.

## Three kinds of assertion

A **precondition** is written `pre(expr)` after the declarator. It is checked after the arguments have initialized the parameters and before the function body runs. A **postcondition** is written `post(expr)` or `post(r: expr)`. It is checked when the function returns normally, after local variables are destroyed and before the parameters are. `r` is a **result binding** that names the returned object. An **assertion statement** is written `contract_assert(expr);` and works like any other statement.

```cpp
#include <contracts>

int isqrt(const int x)
  pre(x >= 0)
  post(r: r * r <= x && (r + 1) * (r + 1) > x)
{
  int r = 0;
  while ((r + 1) * (r + 1) <= x) ++r;
  contract_assert(r >= 0);
  return r;
}
```

`contract_assert` is a full keyword. It was not named `assert` so that it would not clash with the `<cassert>` macro. `pre` and `post` are identifiers with special meaning, so `int pre = 0;` is still valid. You can write any number of `pre` and `post` specifiers in any order, and each kind is evaluated in the order it was written. A postcondition is never checked when the function exits by an exception or by `longjmp`.

## Where function contract specifiers go

Specifiers belong to a function's **first declaration**. A later declaration may leave them out or repeat the whole sequence, which must match the original under the ODR. It may not repeat only part of the sequence, and it may not add specifiers that the first declaration lacked. If two translation units each contain a first declaration and the sequences differ, the program is ill-formed, no diagnostic required.

The specifiers are not part of the function's type. Overload resolution ignores them, so two templates that differ only in their contracts are ambiguous. A pointer to function, a pointer to member function, or a function type alias cannot carry specifiers. A call through a pointer still checks the target's assertions, because they belong to the function rather than to the expression used to call it.

In C++26 these declarations may not have specifiers:

- a virtual function;
- a deleted function;
- a function defaulted on its first declaration. `T::T() = default;` written after `T();` in the class is not a first declaration, but it may not add specifiers either.

Contracts on virtual functions were adopted into the C++29 working draft (P3097R3) in June 2026. Under that design, a virtual call checks the statically chosen function's preconditions and then the final overrider's. None of that is in C++26.

Lambdas, constructors, destructors, `main`, and coroutines may all have contracts. A lambda's specifiers go in the lambda declarator and apply to its call operator. A name used only inside a contract assertion cannot trigger an implicit capture, so `[=] pre(i > 0) {}` is ill-formed unless `i` is captured explicitly or used elsewhere in the body. That rule keeps adding a check from changing a closure's layout. In a coroutine, a predicate may not contain `co_await` or `co_yield`, and a postcondition may not odr-use a non-reference parameter, because the coroutine works on mutable copies of its parameters.

## Predicates see a const world

Inside a predicate, an id-expression that names a variable declared outside the assertion has `const` type. This covers parameters, locals, globals, and anything reached through a reference. `this` becomes a pointer to const, and the result binding is a const lvalue. Rather than banning side effects, the language makes the common accidental mutations fail to compile.

```cpp
struct Buffer {
  int n = 0;
  int size() { return n; }               // forgot const
  int csize() const { return n; }
};

void use(Buffer& b) pre(b.csize() > 0);  // OK
// void bad(Buffer& b) pre(b.size() > 0);  // error: b is a const lvalue here
// void inc(int x) pre(++x > 0);           // error: x is const in the predicate
```

The const applies to the name, not to the object. A `mutable` member, a `const_cast`, or a function that modifies a global can still produce a side effect. That is legal, but it is a trap, as the next section shows.

> **Pitfall.** A postcondition that reads a by-value parameter needs that parameter to be declared `const` on every declaration, including declarations that do not mention the postcondition. Without that rule, the body could modify the parameter and the postcondition would check the wrong value. Arrays decay, so `const int a[10]` is `const int*`, not `const int* const`, and still does not qualify.

## Four evaluation semantics

Each evaluation of a contract assertion uses one of four semantics:

- **ignore**: the predicate is not evaluated. It is still odr-used, so it must compile, and templates in it are instantiated.
- **observe**: the predicate is checked. On a violation, the contract-violation handler runs, and if it returns, execution continues after the assertion.
- **enforce**: the predicate is checked. On a violation, the handler runs, and if it returns, the program is *contract-terminated*.
- **quick-enforce**: the predicate is checked. On a violation, the program is contract-terminated immediately, without calling the handler.

Observe, enforce, and quick-enforce are the checking semantics, and enforce and quick-enforce are the terminating ones. Contract termination means calling `std::terminate`, calling `std::abort`, or simply stopping execution, and the choice is implementation-defined. Which semantic applies is implementation-defined *for each evaluation*. The standard recommends that implementations offer an all-ignore mode and an all-enforce mode, with enforce as the default. GCC selects the semantic with `-fcontract-evaluation-semantic=ignore|observe|enforce|quick_enforce`, defaulting to enforce.

A violation happens when the predicate is false, when its evaluation exits via an exception, or, during constant evaluation, when it is not a core constant expression.

> **Standardese.** Under a checking semantic, "it is unspecified whether the predicate is evaluated" ([basic.contract.eval]). The implementation may determine the value another way, with no side effects. Consecutive assertions are "evaluated in sequence", and each may be repeated an implementation-defined number of times, as long as the first occurrences keep their order. So a side effect in a predicate may happen zero, one, or several times, even with enforce.

Checking does not make undefined behaviour inside the predicate safe. If the predicate overflows a signed integer, the compiler may assume that never happens and fold the check away. To stop undefined behaviour *after* a check from reaching back in time and removing the check, the standard places an **observable checkpoint** before each checking evaluation, and another after the handler returns.

## The contract-violation handler

On a violation under observe or enforce, the implementation calls `::handle_contract_violation(const std::contracts::contract_violation&)`. Whether you can replace it is implementation-defined, and `__cpp_lib_replaceable_contract_violation_handler` reports the answer. `<contracts>` is freestanding. The `contract_violation` object cannot be copied, and you cannot create one yourself. It provides these observers:

- `kind()`, which returns `assertion_kind::pre`, `post`, or `assert`;
- `semantic()`, which returns the `evaluation_semantic` used;
- `is_terminating()`;
- `detection_mode()`, which returns `predicate_false` or `evaluation_exception`;
- `comment()`, usually the text of the predicate;
- `location()`, the source location.

`invoke_default_contract_violation_handler(v)` hands the violation to the default handler.

```cpp
#include <contracts>
#include <cstdio>
#include <exception>

void handle_contract_violation(const std::contracts::contract_violation& v) {
  std::fprintf(stderr, "%s:%u: %s\n", v.location().file_name(),
               (unsigned)v.location().line(), v.comment());
  if (v.detection_mode() == std::contracts::detection_mode::evaluation_exception)
    std::fprintf(stderr, "  (the predicate threw)\n");
  std::contracts::invoke_default_contract_violation_handler(v);
}
```

When the predicate throws, the handler runs inside an active implicit handler for that exception, so `std::current_exception()` or `throw;` can reach it. P2900R14 also had an `evaluation_exception()` observer returning `exception_ptr`, but it is not in N5050.

The handler may throw an exception instead of returning. For a precondition or postcondition, the effect is as if the function body exited with that exception. A function-try-block cannot catch it, and in a `noexcept` function the result is `std::terminate`. For `contract_assert`, the exception propagates from the statement like any other throw.

> **Pitfall.** GCC 16 spells the observer `mode()` instead of `detection_mode()`. It reports `predicate_false` even when the predicate threw, although it does call the handler from inside the exception's handler. It also accepts some forms the draft forbids: specifiers on deleted functions, on functions defaulted on their first declaration, and on function pointer declarations, and coroutine postconditions that read parameters. Trust the draft.

## Constant evaluation

Contract assertions are evaluated during constant evaluation too, with a semantic the implementation chooses. A violation there makes the program ill-formed under a terminating semantic. Under observe it produces a diagnostic, and evaluation continues. There is no handler at compile time.

```cpp
constexpr int half(int x) pre(x % 2 == 0) { return x / 2; }

static_assert(half(4) == 2);
// constexpr int a = half(3);
// enforce: error; observe: warning, a == 1; ignore: accepted silently
```

To decide whether a variable is constant-initialized, the implementation pretends that every assertion uses ignore. A failing check therefore cannot quietly turn static initialization into dynamic initialization. If one inline function sees different semantics in different translation units, and a predicate's side effect changes a constant's value, the result is an ODR violation.

## Relation to assert, [[assume]] and the library

`assert` is a macro controlled by `NDEBUG`. It cannot appear on a declaration, and it has no handler. `contract_assert` is a language construct that `NDEBUG` does not affect. An unchecked contract assertion never licenses the optimizer to assume that its predicate holds. That job belongs to `[[assume(expr)]]`, which is the opposite tool: a false assumption is undefined behaviour, while a false contract is a reportable violation. An "assume" semantic was deliberately left out of C++26.

The C++20 contracts design, P0542, was removed in 2019 before it shipped. It used attributes such as `[[expects: x > 0]]`, `[[ensures r: r > 0]]`, and `[[assert: p]]`, with `default`, `audit`, and `axiom` levels, a global build level, and a continuation mode. Violating an unchecked contract was undefined behaviour, which let compilers assume it held. P2900 replaces all of that with plain syntax, no levels, and semantics chosen per evaluation.

C++26 also adds a **hardened implementation**, specified by P3471. In a hardened implementation, a *Hardened preconditions:* clause in the library is checked with a contract assertion that uses a terminating semantic. Examples are `vector::operator[]`, `span::front`, and `optional::operator*`. In a non-hardened implementation, violating one is still undefined behaviour. Whether an implementation is hardened is implementation-defined. GCC 16 defines none of the `__cpp_lib_hardened_*` macros, and its `_GLIBCXX_ASSERTIONS` checks do not go through the contracts machinery.

## What to remember

- `pre`, `post(r: ...)`, and `contract_assert` express redundant checks. A correct program behaves the same whether they are checked or not.
- Specifiers live on the first declaration, are not part of the function type, and in C++26 are banned on virtual, deleted, and first-declaration-defaulted functions.
- Inside a predicate, outside variables, `*this`, and the result binding are const. A postcondition that reads a by-value parameter needs that parameter `const` on every declaration.
- The semantic (ignore, observe, enforce, or quick-enforce) is implementation-defined for each evaluation. Enforce is the recommended default.
- A predicate may be evaluated zero, one, or several times, so keep side effects out of it.
- A throwing predicate is a violation. A throwing handler acts as if the function body threw, so a `noexcept` function terminates.
- During constant evaluation, a violation is an error under a terminating semantic and a diagnostic under observe.
- Contracts never feed the optimizer; `[[assume]]` does. Library hardening reuses the machinery with a terminating semantic.
- GCC 16 support is experimental and deviates in a few places: it names the observer `mode()` and accepts some ill-formed declarations.

## Concept Map Outline

- **Contracts (C++26):** Redundant checks via pre, post and contract_assert; how they are checked is chosen by the implementation.
  - **Three assertion kinds:** Preconditions, postconditions and assertion statements, each with a bool predicate.
    - **pre(expr):** Checked after parameters are initialized, before the body runs, in lexical order.
    - **post(r: expr):** Checked on normal return only; r is a const lvalue naming the result object.
    - **contract_assert(expr);:** A full keyword and a statement; unaffected by NDEBUG, unlike the assert macro.
  - **Placement rules:** Specifiers attach to the function's first declaration and are not part of its type.
    - **First declaration:** Later declarations omit them or repeat the same sequence; adding or partly repeating is an error.
    - **Not in the type:** Ignored by overload resolution; pointers to functions and type aliases cannot carry them.
    - **Banned in C++26:** Virtual functions, deleted functions, and functions defaulted on first declaration. Virtual support is C++29 (P3097).
    - **Lambdas and coroutines:** Allowed. Contract-only uses cannot trigger implicit capture; coroutine posts cannot read by-value parameters.
  - **Const predicates:** Outside variables, *this and the result binding are const inside a predicate.
    - **Implicit const:** Calling a non-const member or incrementing a parameter in a predicate is ill-formed.
    - **Const parameters for post:** A by-value parameter read in a postcondition must be const on every declaration.
    - **Side effects:** Still possible via mutable or const_cast; a predicate may run zero, one or several times.
  - **Evaluation semantics:** Implementation-defined per evaluation; enforce is the recommended default.
    - **ignore:** Predicate not evaluated, but still odr-used, so it must compile.
    - **observe:** Checked; on violation the handler runs and execution continues if it returns.
    - **enforce:** Checked; handler runs, then the program is contract-terminated if it returns.
    - **quick-enforce:** Checked; contract-terminated at once without calling the handler.
    - **Constant evaluation:** A violation is ill-formed under a terminating semantic and a diagnostic under observe.
  - **Violation handling:** ::handle_contract_violation receives a const std::contracts::contract_violation&.
    - **Replaceable handler:** Replaceability is implementation-defined; __cpp_lib_replaceable_contract_violation_handler reports it.
    - **Observers:** kind, semantic, is_terminating, detection_mode, comment, location. GCC 16 spells detection_mode as mode.
    - **Throwing predicate:** A violation; the handler runs inside an active handler for that exception.
    - **Throwing handler:** Acts as if the function body threw; in a noexcept function, std::terminate is called.
  - **Related features:** How contracts differ from older and neighbouring mechanisms.
    - **[[assume]]:** A false assumption is UB; contracts never let the optimizer assume an unchecked predicate.
    - **C++20 attributes:** [[expects]], [[ensures]] and [[assert]] with levels were removed in 2019 before shipping.
    - **Library hardening:** In a hardened implementation, library Hardened preconditions are checked with a terminating semantic.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.contract.func], [dcl.contract.res])

Under the C++26 draft, is this declaration well-formed?

```cpp
int isqrt(int x)
  pre(x >= 0)
  post(r: r * r <= x && (r + 1) * (r + 1) > x);
```

A. Well-formed
B. Ill-formed: a postcondition cannot refer to function parameters
C. Ill-formed: the postcondition odr-uses `x`, so `x` must be declared `const` on every declaration
D. Well-formed, but undefined behavior if the body modifies `x`

**Answer (C):** Ill-formed: the postcondition odr-uses `x`, so `x` must be declared `const` on every declaration

**Why:** Postconditions may name parameters, but if a postcondition odr-uses a non-reference parameter, that parameter must have `const` type on every declaration of the function, including declarations without the postcondition. Otherwise the body could change `x` and the check would test a different value from the one the caller passed. Writing `const int x` fixes it. The "undefined behavior" answer is tempting because it describes what would go wrong without the rule, but the language makes the declaration ill-formed instead of leaving it to run-time behavior.

### Question 2 [warmup] ([dcl.contract.func], [expr.call])

With the enforce semantic for every contract assertion, what does this program print?

```cpp
#include <cstdio>
#include <stdexcept>

int parse(const int x) post(r: r > 0) {
  if (x < 0) throw std::invalid_argument("negative");
  return x;
}

int main() {
  try {
    parse(-1);
  } catch (const std::invalid_argument&) {
    std::puts("invalid_argument");
  }
}
```

A. `invalid_argument`
B. A contract-violation diagnostic, then the program is contract-terminated
C. A contract-violation diagnostic, then `invalid_argument`
D. Nothing; `std::terminate` is called because an exception passes through a postcondition

**Answer (A):** `invalid_argument`

**Why:** A postcondition assertion is associated only with exiting the function normally. When `parse` exits via an exception, its postconditions are not evaluated at all, so there is no violation and the exception reaches the handler in `main`. The answers with a diagnostic assume the postcondition is checked on every exit, which is wrong. A postcondition that a function does or does not throw is one of the features P2900 deliberately leaves out.

### Question 3 [warmup] ([expr.call], [basic.contract.eval], [dcl.contract.func])

Assume a checking semantic, and assume each predicate is evaluated exactly once. What does this program print?

```cpp
#include <cstdio>

bool say(const char* s) { std::puts(s); return true; }

int f()
  pre(say("pre a"))
  post(r: say("post b"))
  pre(say("pre c"))
{
  std::puts("body");
  return 0;
}

int main() { f(); }
```

A. `pre a`, `post b`, `pre c`, `body`
B. Nothing: the program is ill-formed because `pre` must come before `post`
C. `pre c`, `pre a`, `body`, `post b`
D. `pre a`, `pre c`, `body`, `post b`

**Answer (D):** `pre a`, `pre c`, `body`, `post b`

**Why:** `pre` and `post` specifiers may appear in any order, so the declaration is fine. The preconditions are evaluated in sequence, in lexical order, after the parameters are initialized and before the body runs. The postconditions are evaluated in sequence after the body returns normally. The `pre a`, `post b`, `pre c` answer reads the specifiers as a single list evaluated left to right. The assumption in the question matters: under a checking semantic it is unspecified whether a predicate is actually evaluated, and an implementation may repeat assertions, so side effects like these `puts` calls are not guaranteed in general.

### Question 4 [tricky] ([expr.prim.id.unqual], [basic.contract.general], [dcl.contract.func])

Which of these declarations is ill-formed under the C++26 draft?

```cpp
struct Buffer {
  int n = 0;
  int size() { return n; }
  int csize() const { return n; }
};

void a(Buffer& b) pre(b.csize() > 0);
void b(Buffer& b) pre(b.size() > 0);
void c(Buffer* p) pre(p != nullptr);
void d(const Buffer& b) post(b.n >= 0);
```

A. `a`
B. `b`
C. `c`
D. `d`

**Answer (B):** `b`

**Why:** Inside a contract predicate, an id-expression that names a variable declared outside the assertion has `const` type, and that includes reference parameters. So `b` is a `const Buffer` lvalue in the predicate, and calling the non-const `size()` on it is ill-formed. In `c`, only the pointer `p` becomes const, which does not stop a comparison. In `d`, the parameter is a reference, so the postcondition does not require it to be declared `const`. The const requirement for postconditions applies only to non-reference parameters.

### Question 5 [tricky] ([basic.contract.eval], [except.terminate], [basic.contract.handler])

Assume the implementation lets you replace the contract-violation handler, and the enforce semantic is used. What happens?

```cpp
#include <contracts>
#include <cstdio>
#include <stdexcept>

void handle_contract_violation(const std::contracts::contract_violation& v) {
  throw std::logic_error(v.comment());
}

void g(int x) noexcept pre(x > 0) {}

int main() {
  try {
    g(0);
  } catch (const std::logic_error&) {
    std::puts("caught");
  }
}
```

A. `std::terminate` is called
B. `caught` is printed: the precondition is checked by the caller, outside the `noexcept` boundary
C. The handler returns via the exception, so the program is contract-terminated without unwinding
D. Undefined behavior

**Answer (A):** `std::terminate` is called

**Why:** If a handler invoked from a function contract assertion exits via an exception, the behavior is as if the function body had exited via that exception. `g` is `noexcept`, so the search for a handler leaves a non-throwing function and `std::terminate` is called. This happens even though implementations may emit precondition checks at the call site, which is why `caught` is tempting. A handler that throws from a plain `contract_assert` instead propagates the exception from that statement.

### Question 6 [tricky] ([expr.prim.lambda.closure], [dcl.contract.func])

Under the C++26 draft, which lambda makes the program ill-formed?

```cpp
void test() {
  int i = 1;
  auto f1 = [i] pre(i > 0) {};
  auto f2 = [=] pre(i > 0) {};
  auto f3 = [=] { contract_assert(i > 0); (void)i; };
  auto f4 = [&] { return i; };
}
```

A. `f1`: explicit captures cannot be used in a precondition
B. `f2`
C. `f3`: `contract_assert` cannot appear in a lambda body
D. None of them

**Answer (B):** `f2`

**Why:** If every potential reference to an implicitly captured local entity appears inside contract assertions, the program is ill-formed. Adding a check must never cause a new capture, because a capture would change the closure's layout. `f2` uses `i` only in its precondition, so it breaks the rule. `f1` captures `i` explicitly, and `f3` also uses `i` outside the assertion, so both are fine. GCC 16 rejects `f2` with "not implicitly captured by a contract assertion".

### Question 7 [standardese] ([basic.contract.eval], [expr.const], [intro.compliance.general])

Under the C++26 draft, what is true of the declaration of `a`?

```cpp
constexpr int half(int x) pre(x % 2 == 0) { return x / 2; }

constexpr int a = half(3);
```

A. It is always ill-formed, because a precondition is false in a constant expression
B. `a` falls back to dynamic initialization, and the handler runs at program startup
C. It is ill-formed if the evaluation uses enforce or quick-enforce. With observe, a diagnostic is issued and `a` is 1. With ignore, it is accepted silently
D. It is always accepted, because contract assertions are not evaluated during constant evaluation

**Answer (C):** It is ill-formed if the evaluation uses enforce or quick-enforce. With observe, a diagnostic is issued and `a` is 1. With ignore, it is accepted silently

**Why:** Contract assertions are evaluated during constant evaluation, with an implementation-chosen semantic. A violation in a manifestly constant-evaluated context makes the program ill-formed under a terminating semantic. Under observe, the implementation must issue a diagnostic but keeps going. The dynamic-initialization answer is wrong because constant-initializability is decided as if every assertion used ignore, so `a` is still constant-initialized, and there is no handler at compile time. GCC 16 shows exactly this pattern: an error under enforce and quick_enforce, a warning under observe, and silence under ignore.

### Question 8 [standardese] ([dcl.contract.func], [dcl.fct.def.coroutine], [expr.await])

In C++26, as specified in the final draft N5050, which of these may *not* have a function contract specifier?

A. A constructor, as in `S(int n) pre(n > 0);`
B. A coroutine whose precondition reads a by-value parameter
C. The function `main`
D. A virtual member function, as in `virtual void f(int i) pre(i > 0);`
E. A redeclaration that repeats exactly the same specifiers as the first declaration

**Answer (D):** A virtual member function, as in `virtual void f(int i) pre(i > 0);`

**Why:** In C++26, [dcl.contract.func] says a virtual function, a deleted function, or a function defaulted on its first declaration shall not have a function-contract-specifier-seq. Contracts for virtual functions (P3097R3) were adopted only into the C++29 working draft, in June 2026. Constructors, coroutines, and `main` may have contracts. Coroutines are restricted only in that a postcondition may not odr-use a non-reference parameter, and a predicate may not contain `co_await`. A non-first declaration may either omit the specifiers or repeat the same sequence.

# Static reflection

> C++26 lets a program ask the compiler about its own declarations at compile time. The `^^` operator turns a construct into a `std::meta::info` value, `<meta>` functions query and transform those values, and a splice `[: r :]` turns a value back into code.

- **Source:** C++ Atlas (https://cppatlas.com/topics/reflection)
- **Track:** C++26
- **Estimated reading time:** 15 minutes
- **ISO C++ clauses:** [expr.reflect] (https://eel.is/c++draft/expr.reflect), [basic.splice] (https://eel.is/c++draft/basic.splice), [basic.types.general] (https://eel.is/c++draft/basic.types.general), [expr.const.imm] (https://eel.is/c++draft/expr.const.imm), [expr.const.reflect] (https://eel.is/c++draft/expr.const.reflect), [stmt.expand] (https://eel.is/c++draft/stmt.expand), [dcl.attr.annotation] (https://eel.is/c++draft/dcl.attr.annotation), [meta.syn] (https://eel.is/c++draft/meta.syn), [meta.reflection.access.context] (https://eel.is/c++draft/meta.reflection.access.context), [meta.reflection.member.queries] (https://eel.is/c++draft/meta.reflection.member.queries), [meta.reflection.define.aggregate] (https://eel.is/c++draft/meta.reflection.define.aggregate)
- **cppreference links:** [Reflection TS (the earlier, type-based design)](https://en.cppreference.com/w/cpp/experimental/reflect), [consteval specifier](https://en.cppreference.com/w/cpp/language/consteval), [Constant expressions](https://en.cppreference.com/w/cpp/language/constant_expression)
- **Prerequisites:** constant-expressions, type-traits-and-metaprogramming, template-instantiation-and-specialization, constexpr-in-cpp26

## The one idea

Reflection gives you a value that stands for a piece of your program: a type, a variable, a data member, an enumerator, a function, a namespace. You can store that value, pass it to functions, put it in a `std::vector`, and compare it. When you are done computing, you **splice** it back, and the compiler treats the splice as if you had written the name of the thing it stands for.

All of this happens during constant evaluation. A reflection value never exists at run time, so reflection costs nothing at run time and cannot leak compiler internals into a binary.

This is C++26. The core paper is P2996R13, adopted in June 2025, together with P3394R4 (annotations), P3293R3 (splicing base class subobjects), P3096R12 (reflecting function parameters), P3491R3 (`define_static_array` and friends), P3560R2 (errors as exceptions), P3289R1 (`consteval` blocks) and P1306R5 (expansion statements). Everything here follows N5050, the final C++26 draft sent to the international ballot. That ballot closed in October 2026 and was reported as not approved, so check the status before you quote this as published ISO C++. GCC 16 lists every one of these papers except P3289 as implemented, and `consteval` blocks work as well. Reflection itself needs `-std=c++26 -freflection`. Expansion statements work with `-std=c++26` alone. Clang 21 has no reflection support. Every example below was compiled with GCC 16.2.

> **Mental model.** `^^` lifts a construct into a value of type `std::meta::info`. Ordinary `consteval` code computes with those values. `[: :]` lowers a value back into a construct. Between the lift and the lower, reflection is just constant-expression programming.

## Lifting and lowering

The reflection operator accepts `^^::` for the global namespace, a namespace or template name, a type-id, or an id-expression naming a variable, function, enumerator, structured binding, or non-static data member. Its result is a prvalue of type `std::meta::info`, a scalar type whose values can be compared with `==` and `!=` but not ordered. A value-initialized `info` holds the unique **null reflection**.

```cpp
#include <meta>

constexpr std::meta::info t = ^^int;     // a reflection of the type int
typename [:t:] answer = 42;              // splice it back: declares an int

struct Point { int x; int y; };
constexpr std::meta::info ry = ^^Point::y;          // reflects the data member y
int read_y(const Point& p) { return p.[:ry:]; }     // member access through a splice

static_assert(std::meta::is_type(t));
static_assert(std::meta::identifier_of(ry) == "y");
static_assert(std::meta::type_of(ry) == ^^int);
static_assert(^^Point::x != ^^Point::y);            // reflections compare by identity
```

A splice `[: r :]` requires `r` to be a constant expression. Where the grammar cannot tell what kind of thing the splice produces, you disambiguate as you do with dependent names: write `typename [:r:]` for a type and `template [:r:]` for a template. `obj.[:m:]` accesses a member, and `[:r:]` alone is an expression when `r` reflects a variable, function, or enumerator.

Reflections keep aliases apart. With `using Int = int;`, `^^Int` reflects the type alias and is not equal to `^^int`. `std::meta::dealias(^^Int)` gives `^^int`.

> **Pitfall.** `^^` takes the longest token sequence that forms a type-id. So `r == ^^int && ok` parses as `r == ^^(int&&) ok` and does not compile. The draft's own example shows this, and also `^^int & true`. Write `(^^int) && ok`.

## Why it is compile-time only

N5050 introduces **consteval-only types** in [basic.types.general]. `std::meta::info` is one, and so is any pointer, reference, array, or class that contains one, including `std::vector<std::meta::info>`. Every object of such a type must be a `constexpr` variable, a template parameter object, or an object whose lifetime begins and ends inside one constant evaluation. A function whose type mentions a consteval-only type must be an immediate function.

```cpp
#include <meta>

consteval std::size_t field_count(std::meta::info type) {
  return std::meta::nonstatic_data_members_of(
      type, std::meta::access_context::unchecked()).size();
}

struct P { int a; double b; };
static_assert(field_count(^^P) == 2);

int main() {
  // std::meta::info bad = ^^P;          // error: a run-time object of consteval-only type
  constexpr std::meta::info r = ^^P;     // OK: a constexpr variable
  return field_count(r) == 2 ? 0 : 1;    // OK: the call is folded to a constant
}
```

A plain `constexpr` function with an `info` parameter is ill-formed, because it is not immediate. A `constexpr` function *template*, or a lambda, escalates to an immediate function automatically when it touches a reflection.

> **Standardese.** [expr.const.imm] defines an immediate function as one declared `consteval`, or an immediate-escalating function whose type is consteval-only or whose body uses an immediate-escalating expression. Only lambdas, defaulted special members, and specializations of `constexpr` templates are immediate-escalating. That is why `constexpr bool f(std::meta::info)` is an error while `template<class T> constexpr bool f(T)` is fine.

## Querying with `<meta>`

`<meta>` declares more than two hundred `consteval` functions in `std::meta`. They fall into a few families:

- **names**: `identifier_of`, `has_identifier`, `display_string_of`, `source_location_of`;
- **queries**: `type_of`, `parent_of`, `is_public`, `is_static_member`, `is_noexcept`, `has_default_member_initializer`, and many more;
- **members**: `members_of`, `bases_of`, `nonstatic_data_members_of`, `static_data_members_of`, `enumerators_of`, `parameters_of`;
- **layout**: `offset_of`, `size_of`, `alignment_of`, `bit_size_of`;
- **templates**: `template_of`, `template_arguments_of`, `can_substitute`, `substitute`;
- **values**: `reflect_constant`, `reflect_object`, `extract`, `constant_of`;
- **type traits**: an `info`-based twin for every standard trait, such as `is_class_type`, `remove_cvref`, and `is_constructible_type`.

When a function cannot produce a meaningful result, it throws `std::meta::exception` (P3560). If the exception escapes a constant evaluation, the expression is not constant and the program is ill-formed. Inside your own `consteval` code you can catch it.

```cpp
#include <meta>
#include <vector>

constexpr std::meta::info vi = std::meta::substitute(^^std::vector, {^^int});
static_assert(vi == ^^std::vector<int>);
typename [:vi:] numbers{1, 2, 3};        // a std::vector<int>

constexpr std::meta::info c = std::meta::reflect_constant(42);
static_assert(std::meta::extract<int>(c) == 42);
static_assert(std::meta::type_of(c) == ^^int);

consteval bool has_name(std::meta::info r) {
  try {
    (void)std::meta::identifier_of(r);
    return true;
  } catch (const std::meta::exception&) {
    return false;                        // identifier_of throws for unnamed constructs
  }
}
static_assert(has_name(^^numbers));
static_assert(!has_name(^^int));
```

`int` has no identifier in this sense: for a type, `has_identifier` is true only for an unqualified class or enumeration type without template arguments, or one with a typedef name for linkage purposes. Use `display_string_of` when you just want something printable. Its text is implementation-defined.

### Access is an explicit argument

Every member query takes a `std::meta::access_context`. `access_context::current()` checks access as if from the point where you wrote the call. `unprivileged()` checks from the global namespace, and `unchecked()` ignores access entirely. A reflection library cannot quietly read private members. The caller has to opt in, and a code reviewer can see where they did.

## From metadata back to code

Iterating over members needs a loop whose body is instantiated once per element, because each member has a different type. That loop is the **expansion statement**, `template for`. An enumerating expansion statement walks a braced list of expressions. A destructuring expansion statement walks anything that structured bindings accept, such as a tuple or an aggregate. An iterating expansion statement walks a range whose size is a constant. `break` and `continue` work as in a normal loop.

A `std::vector<std::meta::info>` cannot outlive the constant evaluation that created it, so it cannot serve as a `constexpr` range for `template for`. `std::define_static_array` copies the elements into a static array and returns a `span` over it, which can.

```cpp
#include <meta>
#include <string_view>
#include <cstdio>

template <class E>
  requires std::is_enum_v<E>
constexpr std::string_view enum_name(E value) {
  template for (constexpr std::meta::info e :
                std::define_static_array(std::meta::enumerators_of(^^E))) {
    if (value == [:e:]) return std::meta::identifier_of(e);
  }
  return "<unnamed>";
}

enum class Color { red, green, blue };

int main() {
  Color c = Color::blue;                 // a run-time value
  std::puts(enum_name(c).data());        // prints blue
  static_assert(enum_name(Color::red) == "red");
}
```

`enum_name` takes a run-time value, yet it is still a `constexpr` function. The reflections are used only inside the constant initializer of the loop variable `e`, and what survives into run time is a chain of comparisons against enumerator constants and pointers to static strings. The returned `string_view` is null-terminated, because the standard guarantees that every name string from `std::meta` is.

The same pattern prints a struct generically. Because the context is `current()` inside a function template, private members of the argument are skipped.

```cpp
#include <meta>
#include <iostream>

template <class T>
void print_fields(const T& obj) {
  constexpr auto ctx = std::meta::access_context::current();
  template for (constexpr auto m :
                std::define_static_array(std::meta::nonstatic_data_members_of(^^T, ctx))) {
    std::cout << std::meta::identifier_of(m) << " = " << obj.[:m:] << '\n';
  }
}

struct Order {
  int id = 7;
  double price = 9.5;
private:
  int secret = 42;                       // not visible from print_fields
};

int main() { print_fields(Order{}); }    // prints id = 7, then price = 9.5
```

### Annotations

P3394 adds **annotations**, written `[[=expr]]`, where `expr` is any constant expression of structural type. Unlike attributes, the compiler does not interpret them. They exist so that reflection code can read them. Each annotation is a distinct entity, so `[[=1, =1]]` attaches two annotations. Annotations accumulate across redeclarations, and `annotations_of` returns them all.

```cpp
#include <meta>
#include <iostream>

struct Skip {};
struct Width { int chars; };

struct Config {
  [[=Width{6}]] int port = 8080;
  [[=Skip{}]] int cache_handle = 0;
  int max_connections = 64;
};

template <class T>
void dump(const T& obj) {
  constexpr auto ctx = std::meta::access_context::current();
  template for (constexpr auto m :
                std::define_static_array(std::meta::nonstatic_data_members_of(^^T, ctx))) {
    if constexpr (std::meta::annotations_of_with_type(m, ^^Skip).empty()) {
      constexpr auto w = std::define_static_array(
          std::meta::annotations_of_with_type(m, ^^Width));
      std::cout << std::meta::identifier_of(m) << ": ";
      if constexpr (!w.empty())
        std::cout.width(std::meta::extract<Width>(w[0]).chars);
      std::cout << obj.[:m:] << '\n';
    }
  }
}

int main() { dump(Config{}); }  // prints port, padded to 6 columns, then max_connections
```

The annotation value must be usable as a template argument. `Rename{"name"}` with a `const char*` member fails, because a pointer to a string literal is not a permitted constant. Wrap the text with `std::define_static_string` instead.

## Generating types with `define_aggregate`

C++26 reflection can create one kind of declaration: the definition of a previously incomplete class as a plain aggregate. `data_member_spec` describes a member (type, name, alignment, bit-width, `no_unique_address`, annotations). `define_aggregate` takes an incomplete class and a list of member descriptions, and produces an **injected declaration** that completes the class.

An injected declaration is a side effect on the program. It may come only from the evaluation of a `consteval` block, a declaration of the form `consteval { ... }`. Calling `define_aggregate` from a `constexpr` variable's initializer is not a constant expression. A `consteval` block also may not sit inside the class it defines.

```cpp
#include <meta>
#include <array>
#include <vector>
#include <cstdio>

template <class T, std::size_t N>
struct SoA {
  struct Columns;
  consteval {
    std::vector<std::meta::info> specs;
    for (std::meta::info m : std::meta::nonstatic_data_members_of(
             ^^T, std::meta::access_context::unchecked())) {
      std::meta::info column = std::meta::substitute(
          ^^std::array, {std::meta::type_of(m), std::meta::reflect_constant(N)});
      specs.push_back(std::meta::data_member_spec(
          column, {.name = std::meta::identifier_of(m)}));
    }
    std::meta::define_aggregate(^^Columns, specs);
  }
  Columns data;
};

struct Particle { float x; float y; int id; };

int main() {
  SoA<Particle, 1024> ps{};
  ps.data.x[3] = 1.5f;                   // x is std::array<float, 1024>
  ps.data.id[3] = 9;                     // id is std::array<int, 1024>
  std::printf("%zu\n", ps.data.y.size()); // prints 1024
}
```

That is a struct-of-arrays transform in about fifteen lines, with member names preserved. Inside the `consteval` block, an ordinary `for` loop over a `std::vector` is fine, because the whole block is one constant evaluation.

## Limits worth knowing

- C++26 reflection reads declarations, but the only code it writes is aggregate definitions. It cannot inject functions, statements, or arbitrary members. Token-sequence injection is proposed for a later standard.
- `members_of` sees only declarations that precede the point of evaluation. Inside a class's own definition, the class is incomplete, and asking for its members throws.
- Function bodies and expressions cannot be reflected. Only declarations and the entities they introduce can.
- Because `members_of` depends on which declarations precede the evaluation, the same query can answer differently in two translation units. An inline function or template that depends on the answer then violates the ODR.
- `display_string_of` and `source_location_of` are only loosely specified. Do not compare their output across compilers.

## What to remember

- `^^x` gives a `std::meta::info`. `[: r :]` turns it back into code, with `typename` or `template` to disambiguate.
- `info` is a consteval-only type, so every object of it is `constexpr` or lives inside one constant evaluation. A non-template `constexpr` function cannot take one.
- `<meta>` functions are `consteval` and report failure by throwing `std::meta::exception`. An uncaught exception makes the expression non-constant.
- Member queries take an `access_context`: `current()`, `unprivileged()`, or the explicit escape hatch `unchecked()`.
- `template for` instantiates its body once per element. Use `std::define_static_array` to turn a `vector<info>` into something it can walk.
- `define_aggregate` completes an incomplete class, and only from inside a `consteval { }` block.
- `[[=v]]` annotations are user data for reflection. Every annotation counts separately.
- GCC 16 implements all of it behind `-std=c++26 -freflection`. Clang 21 does not implement it yet.

## Concept Map Outline

- **Static reflection (C++26):** P2996 and companions: compile-time values that represent program constructs, queried with <meta> and spliced back into code.
  - **Lift and lower:** ^^ turns a construct into a std::meta::info; [: r :] turns a constant info back into code.
    - **^^ operator:** Accepts ::, namespaces, templates, type-ids and id-expressions; parses the longest possible type-id.
    - **Splicers:** [:r:] needs a constant expression; add typename or template to disambiguate, obj.[:m:] for members.
    - **Aliases stay distinct:** ^^Int != ^^int for using Int = int; dealias gives the underlying type.
  - **Compile time only:** Reflection values never exist at run time, so they cost nothing there.
    - **Consteval-only types:** info and anything containing it may only be constexpr, a template parameter object, or live inside one evaluation.
    - **Immediate functions:** A function with an info in its type must be consteval or immediate-escalating, such as a constexpr template.
    - **meta::exception:** Metafunctions throw on bad input; an uncaught throw makes the expression non-constant (P3560).
  - **Querying <meta>:** Over two hundred consteval functions in std::meta.
    - **Names:** identifier_of throws without has_identifier; display_string_of text is implementation-defined.
    - **Members:** members_of, nonstatic_data_members_of, enumerators_of, bases_of return vector<info> in declaration order.
    - **access_context:** current(), unprivileged() or unchecked(): private members appear only if the caller opts in.
    - **Values and templates:** reflect_constant and extract convert values; substitute builds template specializations.
  - **Writing code:** Turning computed reflections into declarations and statements.
    - **template for:** P1306 expansion statement: body instantiated per element; break and continue are allowed.
    - **define_static_array:** Copies a vector<info> into static storage so template for can iterate it.
    - **define_aggregate:** Completes an incomplete class from data_member_spec descriptions, only inside a consteval block.
    - **consteval blocks:** consteval { ... } runs code at namespace or class scope; the only place injected declarations may come from.
  - **Annotations:** P3394: [[=expr]] attaches structural constants that only reflection reads.
    - **Every one counts:** [[=1, =1]] gives two annotations; redeclarations add more to the same entity.
    - **Reading them:** annotations_of and annotations_of_with_type, then extract<T> to get the value.
  - **Limits and support:** What C++26 reflection does not do, and where it compiles.
    - **No general injection:** Only aggregate definitions can be generated; no functions, statements or expression reflection.
    - **Order matters:** Queries see only preceding declarations, so results can differ by translation unit.
    - **GCC 16:** Implemented behind -std=c++26 -freflection; expansion statements need only -std=c++26. Clang 21 lacks it.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.types.general], [expr.const.imm])

Under the C++26 draft, what happens with this program?

```cpp
#include <meta>

int main() {
  std::meta::info r = ^^int;
  (void)r;
}
```

A. It is ill-formed: `std::meta::info` is a consteval-only type, so `r` must be a `constexpr` variable
B. It compiles and `r` holds a reflection of `int` at run time
C. It compiles, but `r` holds the null reflection at run time
D. Undefined behavior: reflections are only valid during compilation

**Answer (A):** It is ill-formed: `std::meta::info` is a consteval-only type, so `r` must be a `constexpr` variable

**Why:** [basic.types.general] makes `std::meta::info` a consteval-only type. Every object of such a type must belong to a `constexpr` variable, be a template parameter object, or live entirely within one constant evaluation. `r` is an ordinary automatic variable in `main`, so the program is ill-formed, and GCC 16 rejects it. Writing `constexpr std::meta::info r = ^^int;` fixes it. There is no run-time representation of a reflection at all, which is why the "holds a reflection at run time" answer is wrong.

### Question 2 [warmup] ([stmt.expand], [stmt.cont])

What does this C++26 program print?

```cpp
#include <cstdio>
#include <tuple>
#include <type_traits>

int main() {
  template for (auto x : std::tuple{1, 2.5, 'c'}) {
    if constexpr (std::is_same_v<decltype(x), double>) continue;
    std::printf("%d ", static_cast<int>(x));
  }
  std::puts("");
}
```

A. `1 2 99`
B. `1 99`
C. Nothing; it is ill-formed because `continue` cannot appear in an expansion statement
D. Nothing; it is ill-formed because `x` would need a single type for all elements

**Answer (B):** `1 99`

**Why:** `std::tuple` has no `begin` or `end`, so this is a destructuring expansion statement. The body is instantiated once per element, with `x` of type `int`, then `double`, then `char`. In the `double` copy the `if constexpr` branch is taken, and `continue` skips to the next instantiation, which [stmt.cont] allows inside an expansion statement. The output is `1 99 `, with 99 the value of `'c'`. The "single type" answer describes an ordinary range-for, which is exactly what `template for` exists to avoid.

### Question 3 [warmup] ([meta.reflection.access.context], [meta.reflection.member.queries], [meta.reflection.access.queries])

What does this program print? Compile it with `-std=c++26 -freflection` on GCC 16.

```cpp
#include <meta>
#include <cstdio>

struct S {
  int a;
private:
  int b;
public:
  int c;
};

int main() {
  constexpr auto n = std::meta::nonstatic_data_members_of(
      ^^S, std::meta::access_context::current()).size();
  constexpr auto m = std::meta::nonstatic_data_members_of(
      ^^S, std::meta::access_context::unchecked()).size();
  std::printf("%zu %zu\n", n, m);
}
```

A. `3 3`
B. `2 2`
C. `2 3`
D. Nothing; reading private members through reflection is ill-formed

**Answer (C):** `2 3`

**Why:** Member queries return only the members that are accessible from the given `access_context`. `current()` checks access from `main`, which cannot see the private `b`, so only `a` and `c` are returned. `unchecked()` skips access checking entirely, so all three members are returned. Reflection does not forbid seeing private members, but it makes the caller ask for that explicitly, which is why `3 3` is wrong.

### Question 4 [tricky] ([meta.reflection.names], [meta.reflection.exception], [expr.const])

Under the C++26 draft, what is the result of this declaration?

```cpp
#include <meta>

constexpr auto s = std::meta::identifier_of(^^int);
```

A. `s` is a `std::string_view` equal to `"int"`
B. `s` is an empty `std::string_view`
C. The text of `s` is implementation-defined
D. It is ill-formed: `identifier_of` throws `std::meta::exception`, so the initializer is not a constant expression

**Answer (D):** It is ill-formed: `identifier_of` throws `std::meta::exception`, so the initializer is not a constant expression

**Why:** `identifier_of(r)` throws `std::meta::exception` unless `has_identifier(r)` is true. For a type, `has_identifier` is true only for an unqualified class or enumeration type without template arguments, or a type with a typedef name for linkage purposes. `int` is a keyword, not an identifier, so the call throws, the exception escapes the constant evaluation, and the `constexpr` initializer is ill-formed. The implementation-defined answer describes `display_string_of`, which is the function to use for printable names.

### Question 5 [tricky] ([expr.reflect], [meta.reflection.queries])

Under the C++26 draft, what happens with this code?

```cpp
#include <meta>

using Int = int;
constexpr std::meta::info r = ^^Int;
static_assert(r != ^^int && std::meta::is_type_alias(r));
```

A. It is ill-formed: `^^int &&` is parsed as a reflection of the type `int&&`
B. It compiles: `^^Int` reflects the alias, which is a different reflection from `^^int`
C. The `static_assert` fails, because `^^Int` and `^^int` are equal
D. It is ill-formed: a type alias cannot be the operand of `^^`

**Answer (A):** It is ill-formed: `^^int &&` is parsed as a reflection of the type `int&&`

**Why:** [expr.reflect] parses a reflect-expression as the longest token sequence that could form one. `^^int &&` is a valid reflect-expression of the type-id `int&&`, so the condition becomes `r != ^^int&& std::meta::is_type_alias(r)`, which is a syntax error. Parenthesizing as `(r != ^^int) && ...` makes it compile. The tempting "It compiles" answer has the right semantics: `^^Int` does represent the alias and compares unequal to `^^int`, and `dealias(^^Int) == ^^int`.

### Question 6 [tricky] ([expr.const], [expr.const.reflect], [meta.reflection.define.aggregate], [dcl.pre])

Under the C++26 draft, is this translation unit well-formed?

```cpp
#include <meta>

struct S;
constexpr auto r = std::meta::define_aggregate(^^S, {
    std::meta::data_member_spec(^^int, {.name = "x"})});
```

A. Yes: `S` becomes an aggregate with one `int` member `x`
B. Yes, but `S` remains incomplete until the end of the translation unit
C. No: `data_member_spec` requires the name as a `std::u8string`
D. No: `define_aggregate` may produce its injected declaration only while evaluating a `consteval` block

**Answer (D):** No: `define_aggregate` may produce its injected declaration only while evaluating a `consteval` block

**Why:** An expression that would produce an injected declaration is not a core constant expression unless it is the expression of a `consteval` block. So the initializer of `r` is not constant, and the declaration is ill-formed. Writing `consteval { std::meta::define_aggregate(^^S, {...}); }` at namespace scope works. The name may be any ordinary or UTF-8 string, so the `u8string` option is wrong. GCC 16 reports "define_aggregate not evaluated from consteval block".

### Question 7 [standardese] ([basic.types.general], [expr.const.imm])

Under the C++26 draft, which of these declarations is ill-formed?

```cpp
#include <meta>

consteval bool a(std::meta::info r) { return r == ^^int; }

constexpr bool b(std::meta::info r) { return r == ^^int; }

template <class T>
constexpr bool c(T r) { return r == ^^int; }

constexpr auto d = [](std::meta::info r) { return r == ^^int; };
```

A. `a`
B. `b`
C. `c`
D. `d`

**Answer (B):** `b`

**Why:** A function whose type mentions a consteval-only type must be an immediate function. `a` is declared `consteval`. A specialization of the `constexpr` template `c` and the lambda's call operator in `d` are immediate-escalating, so they become immediate functions automatically. `b` is a plain non-template `constexpr` function, which is never immediate-escalating, so it is ill-formed. GCC 16 says "function of consteval-only type must be declared consteval".

### Question 8 [standardese] ([dcl.attr.annotation], [meta.reflection.annotation])

Under the C++26 draft, what does this program print?

```cpp
#include <meta>
#include <cstdio>

[[=1, =2, =1]] void g();
void g [[=3]] ();

int main() {
  constexpr auto n = std::meta::annotations_of(^^g).size();
  std::printf("%zu\n", n);
}
```

A. `2`
B. `3`
C. `4`
D. Nothing; it is ill-formed because `g` is declared twice with different annotations

**Answer (C):** `4`

**Why:** Each annotation, and each instantiation of one, produces a unique annotation, so the repeated `=1` counts twice. For a function, `annotations_of` collects the annotations from every reachable declaration, so the redeclaration adds `=3`. That makes four. The answer `2` assumes annotations deduplicate by value like a set, and `3` forgets one of the two sources. The draft's own example in [dcl.attr.annotation] makes the same point with five annotations.

# Senders and receivers (std::execution)

> C++26's std::execution describes asynchronous work as lazy sender values that complete on exactly one of three channels: value, error, or stopped. Algorithms compose senders, schedulers say where work runs, and nothing happens until a sender is connected to a receiver and started.

- **Source:** C++ Atlas (https://cppatlas.com/topics/senders-and-receivers)
- **Track:** C++26
- **Estimated reading time:** 16 minutes
- **ISO C++ clauses:** [exec.async.ops] (https://eel.is/c++draft/exec.async.ops), [exec.recv] (https://eel.is/c++draft/exec.recv), [exec.opstate] (https://eel.is/c++draft/exec.opstate), [exec.snd] (https://eel.is/c++draft/exec.snd), [exec.sched] (https://eel.is/c++draft/exec.sched), [exec.getcomplsigs] (https://eel.is/c++draft/exec.getcomplsigs), [exec.then] (https://eel.is/c++draft/exec.then), [exec.let] (https://eel.is/c++draft/exec.let), [exec.when.all] (https://eel.is/c++draft/exec.when.all), [exec.starts.on] (https://eel.is/c++draft/exec.starts.on), [exec.continues.on] (https://eel.is/c++draft/exec.continues.on), [exec.on] (https://eel.is/c++draft/exec.on), [exec.sync.wait] (https://eel.is/c++draft/exec.sync.wait), [exec.counting.scopes] (https://eel.is/c++draft/exec.counting.scopes), [exec.task] (https://eel.is/c++draft/exec.task)
- **cppreference links:** [Execution control library](https://en.cppreference.com/w/cpp/execution), [std::execution::then](https://en.cppreference.com/w/cpp/execution/then), [std::execution::let_value](https://en.cppreference.com/w/cpp/execution/let_value), [std::execution::when_all](https://en.cppreference.com/w/cpp/execution/when_all), [std::execution::on](https://en.cppreference.com/w/cpp/execution/on), [std::stop_token](https://en.cppreference.com/w/cpp/thread/stop_token)
- **Prerequisites:** futures-promises-and-async, threads-and-jthread, coroutines, concepts-and-constraints, customization-points-and-niebloids

## The one idea

A **sender** is a value that describes some asynchronous work but does not do it. You build bigger senders out of smaller ones with algorithms such as `then` and `when_all`, and the result is still just a description. Work starts only when a sender is **connected** to a **receiver**, which is the continuation that wants the result, and the resulting **operation state** is **started**. When the work finishes, it calls exactly one of three functions on the receiver: `set_value` with the results, `set_error` with one error, or `set_stopped` with nothing, meaning the work was cancelled.

That design replaces `std::future` for composable asynchrony. A future is eager: the work is already running, so the future needs a shared heap-allocated state and synchronization to hand the result over. A sender is lazy, so the whole pipeline can be assembled first, and the operation state can live in one object, often on the stack, with no allocation and no locks on the happy path.

This is C++26. The core is P2300R10, adopted in June 2024. C++26 also adds P3149R11 (async scopes, `spawn`, and `counting_scope`), P3552R3 (the `std::execution::task` coroutine type), P2079R10 (`parallel_scheduler`), P3175R3 (the reworked `on`), P3284R4 (`write_env` and `unstoppable`), P3481R5 (the three `bulk` variants), and P3557R3 (sender diagnostics computed with `constexpr` exceptions). P3187R1 removed `ensure_started` and `start_detached` from the design before it was adopted, and `split` is not in the final text either. Everything here follows N5050, the final C++26 draft sent to the international ballot. That ballot closed in October 2026 and was reported as not approved, so check the status before you quote this as published ISO C++.

No shipping standard library implements `<execution>`'s sender part yet. GCC 16's libstdc++ does not define `__cpp_lib_senders`, and Clang 21's libc++ does not either. The examples below are written against the N5050 names, and each was compiled and run with GCC 16 against NVIDIA's stdexec reference implementation by mapping `std::execution` to `stdexec`.

> **Mental model.** A sender is a recipe, a receiver is the plate it lands on, and `connect` plus `start` is cooking. The recipe can be copied, combined, and passed around, and no food exists until somebody starts the operation.

## The asynchronous operation contract

[exec.async.ops] states the rules that every sender, receiver, and algorithm relies on.

- An operation is started at most once, and once started it completes **exactly once**.
- It completes with one of three completion operations: a value completion with any number of arguments, an error completion with exactly one argument, or a stopped completion with none.
- The operation state must stay alive, at the same address, until the operation completes. Destroying it earlier is undefined behaviour, and library operation states cannot be copied or moved at all.
- A child operation completes before its parent does. That makes `std::execution` a **structured** concurrency model, in which lifetimes nest like function calls.

A sender advertises what it may complete with through its **completion signatures**, a type such as `completion_signatures<set_value_t(int), set_error_t(std::error_code), set_stopped_t()>`. Algorithms compute their own completion signatures from those of their children at compile time. That is how `when_all` knows what to pass on, and how `sync_wait` knows its return type. In C++26, a sender computes these with a `static consteval` member function template, and an invalid combination throws an exception during constant evaluation. That is how P3557 makes the diagnostics readable.

```text
  sender ──connect(receiver)──► operation state ──start()──► work runs
                                                               │
                         exactly one of: set_value(rcvr, vs...)
                                         set_error(rcvr, e)
                                         set_stopped(rcvr)
```

> **Standardese.** [exec.opstate.general] says that if an `operation_state` object is destroyed during the lifetime of its asynchronous operation, the behaviour is undefined. It also makes a program ill-formed if it copies or moves an operation state created by connecting a library-provided sender.

## Composing with algorithms

Sender factories start a chain: `just(vs...)` completes with values, `just_error(e)` with an error, `just_stopped()` with a stop, and `schedule(sch)` completes on a scheduler's execution resource. Sender adaptors take a sender and return a new one, and each has a pipeable form, so `s | then(f)` means `then(s, f)`.

- `then(f)` calls `f` with the values and sends its result as a value. `upon_error(f)` and `upon_stopped(f)` do the same for the other two channels, turning them back into values.
- `let_value(f)` calls `f` with the values, and `f` returns a *sender*. That sender is connected and started, and its completion becomes the completion of the whole thing. This is the monadic bind, and it is how you write "then do this asynchronous thing next". `let_error` and `let_stopped` exist too.
- `when_all(s1, s2, ...)` starts all of its children and completes with all of their values concatenated. If any child fails or is stopped, it asks the others to stop and forwards the first error or the stop.
- `into_variant`, `stopped_as_optional`, and `stopped_as_error` reshape completions. `bulk`, `bulk_chunked`, and `bulk_unchunked` run a function over an index range.

A sender consumer finally runs the chain. `std::this_thread::sync_wait(s)` connects `s` to its own receiver, starts it, and blocks the calling thread until it completes.

```cpp
#include <execution>
#include <cstdio>

namespace ex = std::execution;

int main() {
  bool ran = false;
  ex::sender auto work =
      ex::when_all(ex::just(1), ex::just(2.5))
    | ex::then([&](int i, double d) { ran = true; return i + d; })
    | ex::let_value([](double sum) { return ex::just(sum * 2); });

  std::printf("%d\n", ran);                         // prints 0: nothing has run yet
  auto [result] = std::this_thread::sync_wait(std::move(work)).value();
  std::printf("%d %.1f\n", ran, result);            // prints 1 7.0
}
```

`sync_wait` returns `std::optional<std::tuple<Values...>>`. A value completion produces an engaged optional, and a stopped completion produces an empty one. An error is thrown: an `exception_ptr` is rethrown as is, an `error_code` is thrown as `std::system_error`, and any other error type is thrown as itself. `sync_wait` requires the sender to have **exactly one** value completion signature, because otherwise it could not name a single tuple type. `sync_wait(just_stopped())` is therefore ill-formed, and so is a sender that might send either an `int` or a `string`. `sync_wait_with_variant` handles that case.

> **Pitfall.** `then` with a callable that returns a sender does not run that sender. It sends the sender object as a value, so the result type of `sync_wait(just() | then([] { return just(42); }))` holds a sender, not an `int`. Use `let_value` whenever the callable returns more work.

## A sender by hand

Writing a sender shows how little machinery there is. This one completes on a different channel depending on its input.

```cpp
#include <execution>
#include <cstdio>
#include <system_error>
#include <utility>

namespace ex = std::execution;

struct parse_sender {
  using sender_concept = ex::sender_tag;
  int input;

  template <class Self, class... Env>
  static consteval auto get_completion_signatures() {
    return ex::completion_signatures<ex::set_value_t(int),
                                     ex::set_error_t(std::error_code),
                                     ex::set_stopped_t()>{};
  }

  template <class Rcvr>
  struct op {
    using operation_state_concept = ex::operation_state_tag;
    Rcvr rcvr;
    int input;
    void start() & noexcept {
      if (input > 0)       ex::set_value(std::move(rcvr), input * 2);
      else if (input == 0) ex::set_stopped(std::move(rcvr));
      else ex::set_error(std::move(rcvr), std::make_error_code(std::errc::invalid_argument));
    }
  };

  template <class Rcvr>
  op<Rcvr> connect(Rcvr rcvr) && { return {std::move(rcvr), input}; }
};

int main() {
  auto r1 = std::this_thread::sync_wait(parse_sender{21});   // optional<tuple<int>> holding 42
  auto r2 = std::this_thread::sync_wait(parse_sender{0});    // empty optional: stopped
  std::printf("%d %d\n", std::get<0>(*r1), r2.has_value());  // prints 42 0
  try {
    std::this_thread::sync_wait(parse_sender{-1});
  } catch (const std::system_error&) {                       // the error_code arrives as system_error
    std::puts("invalid argument");
  }
}
```

The completion functions are `noexcept`, and `start` is too. Errors travel through `set_error`, not through exceptions thrown out of `start`. The operation state holds the receiver by value. Because `sync_wait` keeps the operation state on its own stack frame until completion, nothing here is heap-allocated.

## Where work runs: schedulers

A **scheduler** is a lightweight handle to an execution resource such as a thread pool, an event loop, or a GPU stream. Its only required operation is `schedule(sch)`, which returns a sender that completes on that resource. Standard schedulers include `run_loop`'s scheduler (the loop `sync_wait` drives), `inline_scheduler`, `task_scheduler` (a type-erased scheduler), and `parallel_scheduler`, obtained from `get_parallel_scheduler()`, which guarantees parallel forward progress and has a replaceable backend.

Three adaptors move work between schedulers, and they differ in where the **continuation** runs:

| Adaptor | Starts the work on | Code after it runs on |
| --- | --- | --- |
| `starts_on(sch, s)` | `sch` | wherever `s` completed, normally `sch` |
| `s \| continues_on(sch)` | wherever `s` starts | `sch` |
| `on(sch, s)` | `sch` | the scheduler the whole operation was started on |

`on` is the one to reach for when you want to "run this over there and come back". It finds that resource through the receiver's environment, so under `sync_wait` it returns to the `run_loop` on the waiting thread.

```cpp
#include <execution>
#include <thread>

namespace ex = std::execution;

bool continuation_on_caller(ex::scheduler auto pool, bool use_on) {
  auto caller = std::this_thread::get_id();
  auto here = [caller] { return std::this_thread::get_id() == caller; };
  if (use_on) {
    auto [b] = std::this_thread::sync_wait(ex::on(pool, ex::just()) | ex::then(here)).value();
    return b;                          // true: on() transferred back to sync_wait's run_loop
  }
  auto [b] = std::this_thread::sync_wait(ex::starts_on(pool, ex::just()) | ex::then(here)).value();
  return b;                            // false when pool is a thread pool: then ran on the pool
}
```

Algorithms ask a sender's attributes and a receiver's environment for things like the completion scheduler, the stop token, and an allocator, through queries such as `get_completion_scheduler<set_value_t>`, `get_stop_token`, and `get_allocator`. `read_env(q)` is a sender that completes with the value of query `q` in the current environment, and `write_env(s, env)` changes the environment seen by `s`.

## Cancellation and structured lifetimes

Cancellation is cooperative. A receiver's environment carries a stop token. An operation that can be cancelled checks it or registers a callback, and when stop is requested it completes with `set_stopped`. `when_all` gives its children an `inplace_stop_token` of its own, and requests stop on it as soon as one child fails. `unstoppable(s)` hides the stop token from `s`.

Because every operation completes exactly once and children finish before parents, there is no "fire and forget" in the core model. Work that should outlive the current scope must be **associated** with an async scope. A `counting_scope` counts the operations associated with it. `spawn(s, scope.get_token())` starts `s` eagerly inside the scope, and `spawn_future` does the same but returns a sender for the result. `scope.join()` is a sender that completes when every associated operation has finished. This is what replaced `start_detached` and `ensure_started`, which let work escape without anybody waiting for it.

> **Pitfall.** Destroying a `counting_scope` that has been used but not joined calls `std::terminate`, even if its operations happen to have finished. Before it goes out of scope, `close()` it and wait for `scope.join()`, with `sync_wait` or `co_await`.

Coroutines integrate in both directions. Inside a coroutine whose promise uses `with_awaitable_senders`, `co_await s` suspends until `s` completes and produces its value. An error is thrown, and a stop ends the coroutine without resuming it. `std::execution::task<T>`, from P3552, is a lazy coroutine type that is itself a sender. Its default error completion is `set_error_t(std::exception_ptr)`, it carries an `inplace_stop_token`, and by default it resumes on the scheduler it was started on.

## What is available today

| Implementation | Status |
| --- | --- |
| GCC 16 libstdc++ | No sender support. `__cpp_lib_senders` is not defined. |
| Clang 21 libc++ | No sender support. |
| NVIDIA stdexec | Reference implementation in namespace `stdexec`, tracking the draft closely. |
| Beman `execution` and `task` | Implementations of the C++26 wording from the Beman project. |

The tested stdexec revision differs from N5050 in small ways. Its `sync_wait` lives in `stdexec`, not in `std::this_thread`. Its `exec` namespace still provides `ensure_started`, `start_detached`, and `split` as extensions, along with `exec::static_thread_pool`. None of the code on this page uses those extensions.

## What to remember

- Senders are lazy descriptions. Nothing runs until `connect` and `start`, usually done for you by `sync_wait`, `spawn`, or `co_await`.
- Every operation completes exactly once, on one of three channels: value (any number of arguments), error (exactly one), or stopped (none).
- The operation state must outlive the operation, and destroying it early is undefined behaviour.
- `then` maps values to a value, and `let_value` maps values to a new sender that it runs. Returning a sender from `then` does not run it.
- `sync_wait` needs exactly one value signature. It returns `optional<tuple<...>>`, gives an empty optional when stopped, and throws on error, turning an `error_code` into `system_error`.
- `starts_on` changes where work begins, `continues_on` changes where the continuation runs, and `on` goes over and comes back.
- Detached work goes through an async scope such as `counting_scope`. `ensure_started` and `start_detached` are gone.
- GCC 16 and Clang 21 do not ship it. Use stdexec or Beman.

## Concept Map Outline

- **Senders and receivers:** C++26 std::execution (P2300 and follow-ups): lazy, composable asynchronous work with structured lifetimes.
  - **Core contract:** The rules in [exec.async.ops] that every sender, receiver and algorithm obeys.
    - **Lazy senders:** A sender only describes work; nothing runs until connect and start.
    - **Three channels:** Complete exactly once: set_value with any arguments, set_error with one, set_stopped with none.
    - **Operation state lifetime:** Destroying it before completion is undefined behaviour; library op states cannot be copied or moved.
    - **Completion signatures:** Computed at compile time by a static consteval member; errors are constexpr exceptions (P3557).
  - **Algorithms:** Factories start chains, adaptors transform them, and all adaptors are pipeable.
    - **just and friends:** just, just_error and just_stopped complete immediately on one channel.
    - **then vs let_value:** then sends the callable's result; let_value runs the sender the callable returns.
    - **when_all:** Concatenates child values; on error or stop it requests stop on the other children.
    - **Reshaping:** into_variant, stopped_as_optional, stopped_as_error, upon_error and the bulk family.
  - **Consumers:** Ways to actually connect and start a sender.
    - **sync_wait:** Blocks, returns optional<tuple<...>>, empty when stopped; needs exactly one value signature.
    - **Errors become exceptions:** exception_ptr is rethrown, error_code becomes system_error, other errors are thrown as is.
    - **co_await and task:** Senders are awaitable; std::execution::task<T> (P3552) is a lazy coroutine that is a sender.
  - **Schedulers:** Handles to execution resources; schedule(sch) completes on that resource.
    - **starts_on:** Starts the work on a scheduler; the continuation stays wherever the work completed.
    - **continues_on:** Moves the continuation onto a scheduler after the predecessor completes.
    - **on:** Goes to a scheduler for the work, then transfers back to where it was started.
    - **parallel_scheduler:** From get_parallel_scheduler() (P2079): parallel forward progress, replaceable backend.
  - **Cancellation and scopes:** Cooperative stopping and structured ownership of background work.
    - **Stop tokens:** Read from the receiver's environment; when_all supplies its own inplace_stop_token.
    - **counting_scope:** spawn and spawn_future associate work with a scope; join() waits for all of it (P3149).
    - **Removed: ensure_started:** P3187 removed ensure_started and start_detached; split is not in C++26 either.
  - **Availability:** Status of implementations in late 2026.
    - **No GCC or Clang:** libstdc++ 16 and libc++ 21 do not define __cpp_lib_senders.
    - **stdexec and Beman:** NVIDIA stdexec and the Beman project implement the draft outside namespace std.

## Standardese Quiz Questions

### Question 1 [warmup] ([exec.async.ops], [exec.then])

Under the C++26 draft, what does this program print?

```cpp
#include <execution>
#include <cstdio>

namespace ex = std::execution;

int main() {
  auto work = ex::just() | ex::then([] { std::puts("A"); });
  std::puts("B");
  (void)work;
}
```

A. `A` then `B`
B. `B` only
C. `B` then `A`
D. Either order, because `then` runs on an unspecified thread

**Answer (B):** `B` only

**Why:** Senders are lazy. `just() | then(f)` only builds a description of the work, and `f` runs only after the sender is connected to a receiver and the operation state is started. Nothing here does that, because there is no `sync_wait`, `spawn`, or `co_await`. So only `B` is printed, and `work` is destroyed without ever running. This is the main difference from `std::async`, which starts work immediately.

### Question 2 [warmup] ([exec.sync.wait], [exec.just])

Under the C++26 draft, what is the type of `r`?

```cpp
#include <execution>

auto r = std::this_thread::sync_wait(std::execution::just(1, 2.0));
```

A. `std::optional<std::tuple<int, double>>`
B. `std::tuple<int, double>`
C. `std::variant<std::tuple<int, double>>`
D. `std::expected<std::tuple<int, double>, std::exception_ptr>`

**Answer (A):** `std::optional<std::tuple<int, double>>`

**Why:** `sync_wait` returns `optional` of a tuple of the decayed value types of the sender's single value completion. The tuple holds all values, because a value completion can carry any number of arguments. The optional is empty when the sender completes with `set_stopped`, and errors are thrown rather than returned, so there is no `expected`. The `variant` form is what `sync_wait_with_variant` returns.

### Question 3 [warmup] ([exec.sync.wait], [exec.async.ops])

A sender has completion signatures `set_value_t(int)`, `set_error_t(std::error_code)` and `set_stopped_t()`. At run time it completes with `set_stopped`. What does `std::this_thread::sync_wait` do?

A. It throws `std::system_error`
B. It calls `std::terminate`
C. It returns an empty `std::optional`
D. It blocks forever, because no value ever arrives

**Answer (C):** It returns an empty `std::optional`

**Why:** The stopped channel means that the work was cancelled, which is not an error, so `sync_wait` reports it as a disengaged `optional`. Throwing `std::system_error` is what happens on the error channel when the error is a `std::error_code`. Every started operation completes exactly once, so `sync_wait` always returns or throws.

### Question 4 [tricky] ([exec.then], [exec.let])

Under the C++26 draft, what is true of `r`?

```cpp
#include <execution>

namespace ex = std::execution;

auto r = std::this_thread::sync_wait(
    ex::just() | ex::then([] { return ex::just(42); }));
```

A. It is an `optional<tuple<int>>` holding `42`
B. It is ill-formed: the callable given to `then` may not return a sender
C. It is an `optional` holding a tuple whose element is the sender returned by the lambda, and the value 42 is never produced
D. Undefined behavior: the inner sender is destroyed without being started

**Answer (C):** It is an `optional` holding a tuple whose element is the sender returned by the lambda, and the value 42 is never produced

**Why:** `then` sends whatever its callable returns as a value, and a sender is just an object, so the result is a tuple holding a `just(42)` sender that nobody connects or starts. Destroying a sender that was never connected is fine, so there is no undefined behaviour. To run the returned sender and forward its completion, use `let_value`, which turns the same code into an `optional<tuple<int>>` holding 42.

### Question 5 [tricky] ([exec.sync.wait], [exec.just])

Under the C++26 draft, what happens with this code?

```cpp
#include <execution>

int main() {
  auto r = std::this_thread::sync_wait(std::execution::just_stopped());
  return r.has_value();
}
```

A. It is ill-formed: `sync_wait` mandates exactly one value completion signature, and `just_stopped()` has none
B. It returns 0, because `r` is an empty optional
C. It throws `std::system_error` with `errc::operation_canceled`
D. Undefined behavior: a stopped completion has no value to store

**Answer (A):** It is ill-formed: `sync_wait` mandates exactly one value completion signature, and `just_stopped()` has none

**Why:** `sync_wait` needs a single value completion signature to name its `optional<tuple<...>>` return type. `just_stopped()` has only `set_stopped_t()`, so the result type is ill-formed and the call violates a Mandates element. The empty-optional answer would be correct for a sender that may complete with a value but stops at run time. The same rule rejects a sender with two value signatures, which needs `sync_wait_with_variant`.

### Question 6 [tricky] ([exec.on], [exec.starts.on], [exec.continues.on], [exec.sync.wait])

`pool` is a scheduler for a thread pool whose threads are all distinct from the calling thread. In `std::this_thread::sync_wait(X | std::execution::then(f))`, which choice of `X` makes `f` run on the thread that called `sync_wait`?

A. `std::execution::starts_on(pool, std::execution::just())`
B. `std::execution::just() | std::execution::continues_on(pool)`
C. `std::execution::schedule(pool)`
D. `std::execution::on(pool, std::execution::just())`

**Answer (D):** `std::execution::on(pool, std::execution::just())`

**Why:** `on(sch, sndr)` starts `sndr` on `sch` and, when it completes, transfers execution back to the resource the `on` sender was started on. Under `sync_wait`, that is the `run_loop` driven by the waiting thread. `starts_on` begins on the pool and leaves the completion there. `continues_on(pool)` and `schedule(pool)` both complete on the pool, so `f` runs on a pool thread in all three cases.

### Question 7 [standardese] ([exec.opstate.general], [exec.async.ops])

A program connects a library sender to a receiver, calls `start` on the operation state, and then lets the operation state go out of scope before any completion function has been called. Under the C++26 draft, what is the status of this program?

A. The operation is cancelled, and the receiver gets `set_stopped`
B. Undefined behavior
C. The destructor blocks until the operation completes
D. It is ill-formed

**Answer (B):** Undefined behavior

**Why:** [exec.opstate.general] says that if an operation state object is destroyed during the lifetime of its asynchronous operation, the behaviour is undefined. The operation state is where the running work keeps its data, so nothing is cancelled and nothing waits. It is not ill-formed, because the compiler cannot know when the operation will complete. What is ill-formed is copying or moving an operation state created from a library-provided sender.

### Question 8 [standardese] ([execution.syn], [exec.counting.scopes], [exec.spawn.future], [exec.stopped.opt])

Which of these names is NOT declared in namespace `std::execution` by N5050, the final C++26 draft?

A. `ensure_started`
B. `counting_scope`
C. `spawn_future`
D. `stopped_as_optional`

**Answer (A):** `ensure_started`

**Why:** P3187R1 removed `ensure_started` and `start_detached`, because they let work escape without anyone waiting for it, which breaks structured concurrency. Their role is taken by async scopes from P3149: `counting_scope`, `spawn` and `spawn_future`. `stopped_as_optional` is a standard adaptor that turns a stopped completion into an empty optional value. Reference implementations such as stdexec still offer `ensure_started` as an extension, which is why it may look familiar.

# std::simd data-parallel types

> C++26 adds std::simd::vec and std::simd::mask, portable types that hold a fixed number of elements and apply every operation to all of them at once, so that ordinary-looking C++ compiles to SIMD instructions. The rules for implicit conversions, masks, and loads are what make the code portable.

- **Source:** C++ Atlas (https://cppatlas.com/topics/simd-data-parallel-types)
- **Track:** C++26
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [simd.general] (https://eel.is/c++draft/simd.general), [simd.syn] (https://eel.is/c++draft/simd.syn), [simd.class] (https://eel.is/c++draft/simd.class), [simd.ctor] (https://eel.is/c++draft/simd.ctor), [simd.mask.class] (https://eel.is/c++draft/simd.mask.class), [simd.loadstore] (https://eel.is/c++draft/simd.loadstore), [simd.reductions] (https://eel.is/c++draft/simd.reductions), [simd.flags] (https://eel.is/c++draft/simd.flags)
- **cppreference links:** [Data-parallel types (SIMD)](https://en.cppreference.com/w/cpp/numeric/simd), [std::simd::basic_simd (pre-rename page)](https://en.cppreference.com/w/cpp/numeric/simd/basic_simd), [Parallelism TS v2 SIMD library](https://en.cppreference.com/w/cpp/experimental/simd)
- **Prerequisites:** floating-point-and-numerics, fundamental-types-and-arithmetic-conversions, implicit-conversions, span-and-mdspan, parallel-algorithms-and-execution-policies

## The one idea

A `std::simd::vec<float, 8>` is a small value, like an `int`, that holds eight `float`s. Every operator on it works **element-wise**: `a + b` adds lane 0 to lane 0, lane 1 to lane 1, and so on, and a good compiler turns that into one vector instruction. You write the algorithm once for "a vector of elements", and the width is chosen by the platform or by you.

Two consequences shape the whole library. First, a comparison of two vectors gives you not one `bool` but a vector of them, a **mask**, so ordinary `if` stops working and is replaced by mask reductions and `select`. Second, conversions that would silently lose information in scalar code are rejected, because the library is designed so that code which compiles for one width means the same thing at every width.

This is C++26. The library was merged by P1928R15 from the Parallelism TS 2 `std::experimental::simd`. It was then reshaped by P3430R3 (assorted fixes), P3441R2 (`simd_split` renamed to `chunk`), P3480R6 (vectors are ranges), P2664R11 (permutations, gather, and scatter), and finally P3691R1, which renamed the namespace from `std::datapar` to `std::simd` and the types to `basic_vec`, `vec`, `basic_mask`, and `mask`. Everything here follows N5050, the final C++26 draft sent to the international ballot. That ballot closed in October 2026 and was reported as not approved, so check the status before you quote this as published ISO C++.

GCC 16's libstdc++ ships `<simd>` as experimental, and only for x86 targets with at least SSE2. On other targets, including AArch64, the header declares nothing. It never defines `__cpp_lib_simd`, so you cannot detect it with the feature-test macro. Clang 21's libc++ has no `<simd>`. The examples on this page were compiled and run with GCC 16.2 for x86-64 with `-std=c++26 -O2`, through Compiler Explorer, because the local AArch64 machine could not build them.

> **Mental model.** Think of `vec<T, N>` as `std::array<T, N>` in which every operator is applied element by element, plus a strict rule that nothing converts implicitly unless every possible value survives.

## Vectors, masks, and widths

The two class templates are `basic_vec<T, Abi>` and `basic_mask<Bytes, Abi>`. You normally use their aliases:

| Alias | Meaning |
| --- | --- |
| `vec<T>` | the native width for `T` on the target, for example 4 floats with SSE2 or 16 with AVX-512 |
| `vec<T, N>` | exactly `N` elements, emulated with several registers if needed |
| `mask<T, N>` | the mask type produced by comparing two `vec<T, N>` |

`T` must be a **vectorizable type**: a standard integer or character type, `float`, `double`, `std::float16_t`, `std::float32_t`, `std::float64_t`, or `std::complex<T>` where `T` is one of those floating-point types. `bool` and `long double` are not vectorizable. `vec<T, N>` is guaranteed to be supported for every `N` from 1 to 64, and an implementation may support more, with a limit that can differ by `T`. `V::size()` is a constant, and `V::size` itself is an `integral_constant`, so you can use it in template arguments.

```cpp
#include <simd>
#include <cstdio>

namespace simd = std::simd;

int main() {
  simd::vec<float, 4> v([](int i) { return float(i); });   // {0, 1, 2, 3}
  auto w = v * 2.f;                                         // {0, 2, 4, 6}
  std::printf("%g %d\n", simd::reduce(w), int(w.size()));   // prints 12 4
}
```

The constructor used here is the **generator constructor**. It calls the callable once for each index, in increasing order, passing `integral_constant<simd-size-type, i>`, which converts to `int`. Each lane can therefore be computed from a compile-time index. The generator constructor is `explicit`, so you must write it as direct initialization.

`operator[]` returns the element **by value**. You can read a lane but not assign to one, so `v[0] = 5` does not compile. To change selected lanes, build a new vector with `select`. Since P3480, a `vec` is also a read-only random-access range, so `for (float x : v)` works.

## The value-preserving rule

Every implicit conversion into a `vec` is checked by one rule from [simd.general]: the conversion from `U` to `T` is **value-preserving** if every possible value of `U` can be represented in `T`. The broadcast constructor, which turns a scalar into a vector with every lane equal to it, accepts an arithmetic argument only when its conversion is value-preserving. Binary operators take two `basic_vec` parameters, so a scalar operand must go through that constructor.

```cpp
#include <simd>
#include <utility>

namespace simd = std::simd;
using V = simd::vec<float, 4>;

template <class A, class B>
concept multipliable = requires(A a, B b) { a * b; };

static_assert(multipliable<V, float>);              // 2.f broadcasts
static_assert(!multipliable<V, int>);               // int -> float can lose values
static_assert(multipliable<simd::vec<double, 4>, int>);
static_assert(!multipliable<simd::vec<short, 4>, int>);   // even v + 1 fails for short
static_assert(multipliable<V, decltype(std::cw<2>)>);     // a constant that fits is fine
```

`int` to `float` is not value-preserving, because `float` has only 24 bits of significand. `int` to `short` obviously is not either, which surprises people who write `v + 1` for a `vec<short>`. The fix is to write the literal in the right type, or to pass a compile-time constant such as `std::cw<1>`. A constant is checked for whether its particular value is representable, not whether its whole type is.

The same rule makes vector-to-vector conversion `explicit` whenever it could lose values or would lower the conversion rank. `vec<float, 4>` converts implicitly to `vec<double, 4>`, but going from `vec<double, 4>` to `vec<float, 4>` needs an explicit construction or a cast. The generator's return type is checked the same way, so a generator returning `int` for a `vec<float>` does not compile.

> **Pitfall.** Code that is idiomatic for scalars, such as `x * 2` or `y + 1`, fails to compile for `vec<float>` and `vec<short>`. That is intentional. In scalar code, the usual arithmetic conversions would quietly change the type of the expression, while in SIMD code a changed element type would change the vector's width.

## Masks instead of `bool`

A comparison such as `a < b` returns `mask_type`, one boolean per lane. `basic_mask` has no conversion to `bool`, so `if (a < b)` does not compile. You decide what you mean and say it with a reduction:

- `all_of(m)`, `any_of(m)`, and `none_of(m)` collapse a mask to one `bool`;
- `reduce_count(m)` counts the true lanes;
- `reduce_min_index(m)` and `reduce_max_index(m)` find the first and last true lane.

To make a per-lane choice, the SIMD version of `?:`, use `select(mask, a, b)`. It takes lane `i` from `a` where `mask[i]` is true and from `b` otherwise. Both sides are always computed, so it is a blend, not a branch.

```cpp
#include <simd>
#include <cstdio>

namespace simd = std::simd;
using V = simd::vec<float, 4>;

int main() {
  V v([](int i) { return float(i); });           // {0, 1, 2, 3}
  auto small = v < 2.f;                          // {true, true, false, false}
  // if (small) { }                              // error: no conversion to bool
  std::printf("%d %d %d\n", simd::any_of(small), simd::all_of(small),
              int(simd::reduce_count(small)));   // prints 1 0 2
  V r = simd::select(small, v, V(-1.f));         // {0, 1, -1, -1}
  std::printf("%g %g\n", r[1], r[2]);            // prints 1 -1
}
```

The Parallelism TS spelled this `where(mask, v) = x`. N5050 has no where-expressions. `select`, and the masked overloads of loads, stores, and reductions, replace them.

## Loading and storing

A `vec` is a value, so data moves between it and memory explicitly. N5050 provides two families, and the difference between them is the precondition:

- `unchecked_load<V>(range)` and `unchecked_store(v, range)` require the range to hold at least `V::size()` elements. If the range's size is a constant, a smaller size is ill-formed; otherwise it is undefined behaviour.
- `partial_load<V>(range)` and `partial_store(v, range)` accept any size. Lanes past the end of the range are loaded as `T()`, which is zero, and are not stored.

Both families also take an iterator and a count, or an iterator and a sentinel, and an optional mask that disables lanes. Flags tune them. `flag_convert` allows a load whose element type conversion is not value-preserving, `flag_aligned` promises alignment to `alignment_v<V, U>`, and `flag_overaligned<N>` promises alignment to `N` bytes.

```cpp
#include <simd>
#include <cstddef>
#include <span>

namespace simd = std::simd;

void saxpy(float a, std::span<const float> x, std::span<float> y) {
  using V = simd::vec<float>;                    // native width
  constexpr std::size_t W = V::size();
  std::size_t i = 0;
  for (; i + W <= x.size(); i += W) {            // full vectors
    V xv = simd::unchecked_load<V>(x.data() + i, W);
    V yv = simd::unchecked_load<V>(y.data() + i, W);
    simd::unchecked_store(a * xv + yv, y.data() + i, W);
  }
  std::size_t rest = x.size() - i;               // 0 .. W-1 elements left
  V xv = simd::partial_load<V>(x.data() + i, rest);
  V yv = simd::partial_load<V>(y.data() + i, rest);
  simd::partial_store(a * xv + yv, y.data() + i, rest);
}
```

The main loop uses unchecked operations because the bound already guarantees that enough elements exist. The tail uses partial operations, so no scalar epilogue is needed.

> **Standardese.** [simd.loadstore] specifies a partial load as producing, for each lane `i`, `mask[i] && i < ranges::size(r) ? static_cast<T>(ranges::data(r)[i]) : T()`. Missing lanes are value-initialized. They are never read from memory, so a partial load at the end of an allocation is safe.

## Reductions, math, and permutations

`reduce(v)` combines all lanes with `std::plus<>`. `reduce(v, op)` accepts a commutative operation that takes and returns `vec<T, 1>`, and it combines the lanes as a generalized sum, in an unspecified order and grouping. The masked form `reduce(v, mask, op, identity)` ignores disabled lanes and returns `identity` when no lane is selected. You must supply the identity unless `op` is `plus<>`, `multiplies<>`, `bit_and<>`, `bit_or<>`, or `bit_xor<>`. `reduce_min` and `reduce_max` are shortcuts.

`<simd>` provides `vec` overloads of nearly all of `<cmath>`, including `sqrt`, `sin`, `exp`, `fma`, `hypot`, and the classification functions. It also provides `<bit>` functions such as `popcount` and `countl_zero` for integer vectors, and complex functions for vectors of `std::complex`. `min`, `max`, `minmax`, and `clamp` work element-wise.

P2664 added data movement. `permute(v, idx_fn)` reorders lanes by a compile-time index function, and another overload takes a run-time index vector. `compress(v, mask)` packs the selected lanes to the front, and `expand` does the reverse. `unchecked_gather_from` and `partial_gather_from` read from indexed positions in a range, and `unchecked_scatter_to` and `partial_scatter_to` write to them. `chunk<V>(big)` splits a wider vector into pieces, and `cat(a, b, ...)` joins vectors.

[simd.general] also says that the element-wise operations of a single operator are **unsequenced** with respect to each other. That is what allows a single instruction to perform them. It matters for user-supplied callables, such as the one passed to `reduce`: a callable that depends on order or keeps shared state is not suitable.

## What to remember

- `std::simd::vec<T, N>` is a value holding `N` elements, and every operator acts lane by lane. `vec<T>` picks the native width.
- Implicit conversions must be value-preserving. That rejects `vec<float> * 2` and `vec<short> + 1`. Write `2.f`, cast explicitly, or use `std::cw<2>`.
- Comparisons give masks, not `bool`. Use `all_of`, `any_of`, `none_of`, or `reduce_count`, and use `select` for a per-lane choice.
- `operator[]` reads a lane by value, so you cannot assign through it.
- Use `unchecked_load` and `unchecked_store` for full vectors and `partial_load` and `partial_store` for the tail. Missing lanes load as zero.
- The final names come from P3691: namespace `std::simd`, `basic_vec`, `vec`, `basic_mask`, `mask`. Older papers and pages say `basic_simd` or `std::datapar`.
- GCC 16 ships `<simd>` experimentally for x86 with SSE2 only, and it does not define `__cpp_lib_simd`. Clang 21 has none.

## Concept Map Outline

- **std::simd (C++26):** P1928 and follow-ups: portable data-parallel vector and mask types in namespace std::simd.
  - **Types and widths:** basic_vec<T, Abi> and basic_mask<Bytes, Abi>, used through the vec and mask aliases.
    - **vec<T> and vec<T, N>:** Native width for the target, or exactly N lanes; N from 1 to 64 is always supported.
    - **Vectorizable types:** Standard integers, characters, float, double, fixed-width floats, and complex of those; not bool or long double.
    - **Names from P3691:** Formerly std::datapar, basic_simd and simd_mask; older pages use the old names.
  - **Construction:** Every way of making a vector checks conversions strictly.
    - **Broadcast:** A scalar fills every lane only if its conversion is value-preserving, so vec<float> * 2 fails.
    - **Generator:** Explicit; calls the callable once per lane with integral_constant<i>, in increasing order.
    - **Vector conversions:** Explicit when values could be lost or rank would drop; float to double is implicit.
    - **Read-only lanes:** operator[] returns value_type by value; vectors are read-only ranges (P3480).
  - **Masks:** Comparisons are element-wise and return a mask, never a bool.
    - **No operator bool:** if (a < b) is ill-formed; say what you mean with a reduction.
    - **Mask reductions:** all_of, any_of, none_of, reduce_count, reduce_min_index, reduce_max_index.
    - **select:** select(m, a, b) blends lanes; both sides are computed. Replaces the TS where-expressions.
  - **Memory:** Explicit loads and stores between vectors and contiguous ranges.
    - **unchecked_load and store:** Need at least V::size() elements; too few is ill-formed if constant, otherwise UB.
    - **partial_load and store:** Any size; missing lanes load as T() and are never read or written.
    - **Flags:** flag_convert allows lossy loads; flag_aligned and flag_overaligned<N> promise alignment.
    - **Gather and scatter:** unchecked_ and partial_gather_from and scatter_to use an index vector (P2664).
  - **Algorithms:** Whole-vector operations beyond arithmetic.
    - **reduce:** Generalized sum with a commutative op; masked form returns the identity if no lane is selected.
    - **Math and bits:** Element-wise <cmath>, <bit> and complex functions, plus min, max and clamp.
    - **Permutations:** permute, compress, expand, chunk and cat move lanes around.
  - **Implementation status:** Where <simd> works in late 2026.
    - **GCC 16:** Experimental, x86 with SSE2 only; __cpp_lib_simd is never defined. Nothing on AArch64.
    - **Clang 21:** libc++ has no <simd> yet.

## Standardese Quiz Questions

### Question 1 [warmup] ([simd.ctor], [simd.reductions])

Under the C++26 draft, what does this program print?

```cpp
#include <simd>
#include <cstdio>

int main() {
  std::simd::vec<int, 4> v([](int i) { return i * i; });
  std::printf("%d\n", std::simd::reduce(v));
}
```

A. `14`
B. `6`
C. `9`
D. Nothing; it is ill-formed because the generator must take an `integral_constant` parameter

**Answer (A):** `14`

**Why:** The generator constructor calls the callable once for each lane index `i`, passing `integral_constant<simd-size-type, i>`, which converts implicitly to `int`. So the lanes are 0, 1, 4 and 9. `reduce` with its default `std::plus<>` adds all lanes, giving 14. The answer 6 is the sum of the indices, not of the squares.

### Question 2 [warmup] ([simd.comparison], [simd.mask.class], [simd.mask.reductions])

Under the C++26 draft, what happens with this function?

```cpp
#include <simd>

using V = std::simd::vec<float, 4>;

bool smaller(V a, V b) {
  if (a < b) return true;
  return false;
}
```

A. It returns true if every lane of `a` is less than the matching lane of `b`
B. It returns true if any lane of `a` is less than the matching lane of `b`
C. It is ill-formed: `a < b` is a `basic_mask`, which has no conversion to `bool`
D. It compiles, but which lanes are tested is implementation-defined

**Answer (C):** It is ill-formed: `a < b` is a `basic_mask`, which has no conversion to `bool`

**Why:** Comparing two `vec` objects is an element-wise operation that returns `mask_type`, one boolean per lane. `basic_mask` deliberately has no `operator bool`, because "all lanes" and "any lane" are both plausible meanings. You state which one you want with `all_of(a < b)` or `any_of(a < b)`. For a per-lane choice instead of a branch, use `select`.

### Question 3 [warmup] ([simd.subscr], [expr.assign])

Under the C++26 draft, what happens with this code?

```cpp
#include <simd>

void f() {
  std::simd::vec<float, 4> v(1.f);
  v[0] = 5.f;
}
```

A. Lane 0 becomes 5 and the other lanes stay 1
B. All four lanes become 5
C. It compiles, but the assignment changes a temporary and has no effect
D. It is ill-formed: `operator[]` returns `value_type` by value, which cannot be assigned to

**Answer (D):** It is ill-formed: `operator[]` returns `value_type` by value, which cannot be assigned to

**Why:** `basic_vec::operator[]` returns the element as a prvalue of `value_type`. Assigning to a prvalue of a scalar type is ill-formed, so the code does not compile, and the temporary answer is wrong for the same reason. This is intentional, because a lane inside a register is not an addressable object. To change some lanes, build a new vector with `select`, or use a generator.

### Question 4 [tricky] ([simd.general], [simd.ctor], [simd.binary])

Under the C++26 draft, which line is ill-formed?

```cpp
#include <simd>

using VF = std::simd::vec<float, 4>;
using VD = std::simd::vec<double, 4>;

void f(VF vf, VD vd) {
  auto a = vf * 2.f;   // line A
  auto b = vd * 2;     // line B
  auto c = vf * 2;     // line C
  (void)a; (void)b; (void)c;
}
```

A. Line A only
B. Line B only
C. Line C only
D. Lines B and C

**Answer (C):** Line C only

**Why:** The operands of `basic_vec`'s operators are vectors, so a scalar must be converted by the broadcast constructor. For an arithmetic argument, that constructor requires the conversion to be value-preserving, meaning every value of the source type is representable in the element type. `int` to `double` is value-preserving, but `int` to `float` is not, because `float` cannot represent every 32-bit `int`. So only line C is ill-formed. Writing `2.f` or `std::cw<2>` fixes it.

### Question 5 [tricky] ([simd.loadstore])

Under the C++26 draft, what are the four lanes of `v`?

```cpp
#include <simd>

float data[3] = {1.f, 2.f, 3.f};
auto v = std::simd::partial_load<std::simd::vec<float, 4>>(data, 3);
```

A. `{1, 2, 3, 0}`
B. `{1, 2, 3, 3}`
C. `{1, 2, 3, ?}`, where the last lane is indeterminate
D. Undefined behavior: four elements are read from a three-element array

**Answer (A):** `{1, 2, 3, 0}`

**Why:** A partial load produces `mask[i] && i < size ? data[i] : T()` for each lane, with every lane enabled when no mask is given. Lane 3 is past the end of the range, so it is value-initialized to 0.0f and memory past the array is never read. That is the difference from `unchecked_load`, which requires at least `V::size()` elements and would have undefined behaviour here.

### Question 6 [tricky] ([simd.ctor], [simd.general])

Under the C++26 draft, which of these declarations is well-formed?

```cpp
#include <simd>

using VF = std::simd::vec<float, 4>;
using VD = std::simd::vec<double, 4>;

void f(VF vf, VD vd) {
  VD d1 = vf;      // (1)
  VF f1 = vd;      // (2)
  VF f2(vd);       // (3)
  (void)d1; (void)f1; (void)f2;
}
```

A. Only (1)
B. (1) and (3), but not (2)
C. All three
D. None: different element types never convert

**Answer (B):** (1) and (3), but not (2)

**Why:** The converting constructor between `basic_vec` specializations of the same width is `explicit` exactly when the element conversion is not value-preserving or would lower the conversion rank. `float` to `double` is value-preserving, so (1) is an implicit conversion. `double` to `float` is not, so the constructor is explicit: copy-initialization (2) is ill-formed, while direct-initialization (3) is fine. Without (2) the function compiles.

### Question 7 [standardese] ([simd.general], [simd.expos.abi])

Under the C++26 draft, which of these is guaranteed to name an enabled `basic_vec` specialization on every conforming implementation?

A. `std::simd::vec<bool, 4>`
B. `std::simd::vec<long double, 2>`
C. `std::simd::vec<float, 128>`
D. `std::simd::vec<float, 64>`

**Answer (D):** `std::simd::vec<float, 64>`

**Why:** `deduce-abi-t<T, N>` names an ABI tag for every vectorizable `T` and every `N` from 1 up to an implementation-defined maximum that is not smaller than 64, so `vec<float, 64>` must work. Widths above 64 may or may not be supported. `bool` and `long double` are not vectorizable types at all, so those specializations are disabled everywhere.

### Question 8 [standardese] ([simd.reductions])

Under the C++26 draft, what does this program print?

```cpp
#include <simd>
#include <cstdio>

int main() {
  std::simd::vec<float, 4> v(1.f);
  float r = std::simd::reduce(v, v > 100.f);
  std::printf("%g\n", r);
}
```

A. `4`
B. `0`
C. `1`
D. Nothing; it is ill-formed because the masked `reduce` always needs an explicit identity element

**Answer (B):** `0`

**Why:** The masked `reduce` returns `identity_element` when `none_of(mask)` is true, and no lane exceeds 100 here. For `plus<>`, the default operation, the identity defaults to `T()`, which is 0. An explicit identity is required only for operations other than `plus<>`, `multiplies<>`, `bit_and<>`, `bit_or<>` and `bit_xor<>`. The answer 4 ignores the mask.

# Erroneous behaviour and C++26 language changes

> C++26 adds erroneous behaviour, a new category for code that is wrong but still well-defined, and uses it to take uninitialized reads out of undefined behaviour. Alongside it come several rules that turn old traps into compile errors, plus the small conveniences `_`, `= delete("why")`, computed `static_assert` messages, and `#embed`.

- **Source:** C++ Atlas (https://cppatlas.com/topics/erroneous-behaviour-and-cpp26-language-changes)
- **Track:** C++26
- **Estimated reading time:** 15 minutes
- **ISO C++ clauses:** [defns.erroneous] (https://eel.is/c++draft/defns.erroneous), [intro.abstract] (https://eel.is/c++draft/intro.abstract), [basic.indet] (https://eel.is/c++draft/basic.indet), [dcl.attr.indet] (https://eel.is/c++draft/dcl.attr.indet), [stmt.return] (https://eel.is/c++draft/stmt.return), [expr.delete] (https://eel.is/c++draft/expr.delete), [expr.arith.conv] (https://eel.is/c++draft/expr.arith.conv), [basic.scope.scope] (https://eel.is/c++draft/basic.scope.scope), [dcl.fct.def.delete] (https://eel.is/c++draft/dcl.fct.def.delete), [dcl.pre] (https://eel.is/c++draft/dcl.pre), [dcl.struct.bind] (https://eel.is/c++draft/dcl.struct.bind), [stmt.iter.general] (https://eel.is/c++draft/stmt.iter.general), [cpp.embed] (https://eel.is/c++draft/cpp.embed), [depr.ellipsis.comma] (https://eel.is/c++draft/depr.ellipsis.comma)
- **cppreference links:** [C++ attribute: indeterminate](https://en.cppreference.com/w/cpp/language/attributes/indeterminate), [Undefined behavior](https://en.cppreference.com/w/cpp/language/ub), [Default-initialization](https://en.cppreference.com/w/cpp/language/default_initialization), [static_assert declaration](https://en.cppreference.com/w/cpp/language/static_assert), [Structured binding declaration](https://en.cppreference.com/w/cpp/language/structured_binding), [Function definition (deleted functions)](https://en.cppreference.com/w/cpp/language/function)
- **Prerequisites:** strict-aliasing-and-undefined-behavior, object-lifetime-and-storage, initialization-forms, reference-binding-and-temporaries, structured-bindings, preprocessor-and-translation-phases

## The one idea

Undefined behaviour gives the compiler permission to assume that something never happens. When it does happen anyway, the program can do anything, and optimizers really do delete checks and reorder code on that assumption. C++26 adds a third category between "correct" and "undefined": **erroneous behaviour**. The behaviour is still a bug, but it is *defined*. The program gets a specific, predictable result, and the implementation is encouraged to diagnose it, either while compiling or at run time.

The first and most important use is reading an uninitialized local variable. In C++23 that is undefined behaviour. In C++26 the variable holds an **erroneous value**, a fixed value chosen by the implementation, and reading it is erroneous behaviour. Your program is still wrong, but the optimizer can no longer reason from your mistake.

This is C++26. Erroneous behaviour comes from P2795R5, adopted in March 2024. The other changes covered here are P2748R5, P3144R2, P2864R2, P2865R6, P2169R4, P2573R2, P2741R3, P0963R3, P0609R3, P1061R10, P1967R14, P2809R3 and P3176R1, each named where it appears. Everything here follows N5050, the final C++26 draft sent to the international ballot. That ballot closed in October 2026 and was reported as not approved, so check the status before you quote this as published ISO C++. GCC 16 implements all of these with `-std=c++26`. The one deviation is that it only warns about mixed-enumeration arithmetic, which N5050 makes ill-formed. Clang 21 implements most of them, but it ignores `[[indeterminate]]` with a warning and treats `#embed` in C++ as an extension.

> **Mental model.** Undefined behaviour means the compiler may assume it never happens. Erroneous behaviour means it is a bug, it may be reported, and it still means one particular thing.

## Erroneous values

[basic.indet] now distinguishes two kinds of "garbage". When storage for an object with **automatic** storage duration is obtained, its bytes have **erroneous values**. Each is fixed by the implementation and does not depend on the program's state. Storage from `new`, and any variable or parameter marked `[[indeterminate]]`, starts with **indeterminate values**, as before. Static and thread-local variables are still zero-initialized.

Evaluating an erroneous value is erroneous behaviour. Evaluating an indeterminate value is still undefined behaviour. In both cases, copying an `unsigned char` or `std::byte` is allowed, and the copy inherits the erroneous or indeterminate value.

```cpp
void consume(int);

void f() {
  int a;                      // erroneous value
  int b [[indeterminate]];    // indeterminate value: opted out
  int* p = new int;           // *p has an indeterminate value

  consume(a);                 // erroneous behaviour: defined but wrong
  consume(b);                 // undefined behaviour
  consume(*p);                // undefined behaviour
  delete p;
}
```

`[[indeterminate]]` exists for performance-critical code, such as a large buffer that is about to be overwritten, where you do not want the compiler to spend time initializing it. It may appear only on the definition of a block variable with automatic storage, or on a function parameter, and it must be on the first declaration. Using it is a promise that you will write before you read. If you break the promise, you are back in undefined behaviour.

> **Standardese.** [defns.erroneous] defines erroneous behaviour as "well-defined behavior that the implementation is recommended to diagnose". Its note adds that erroneous behaviour is always the consequence of incorrect program code, and that evaluating a constant expression never exhibits behaviour specified as erroneous in the core language clauses. [intro.abstract] permits an implementation to issue a diagnostic and to terminate the program when an erroneous operation executes. Its recommended practice is to diagnose, and a note accepts diagnostics with false positives.

Constant evaluation is stricter. `constexpr int f() { int x; return x; }` cannot be used in a constant expression, because reading `x` is erroneous behaviour, and anything that exhibits erroneous behaviour is not a core constant expression.

## What GCC 16 does

The standard leaves the erroneous value unspecified. GCC 16 chooses zero. In C++26 mode, when you pass no `-ftrivial-auto-var-init=` option, GCC zero-initializes automatic variables, excluding padding bits, unless they are marked `[[indeterminate]]` or `[[gnu::uninitialized]]`. So a program that read garbage when built with `-std=c++23` reads 0 when built with `-std=c++26`. `-ftrivial-auto-var-init=pattern` chooses a recognizable non-zero pattern instead, which is usually better for finding bugs in tests.

```cpp
#include <cstdio>

[[gnu::noinline]] void scribble() { volatile int junk = 100; (void)junk; }

[[gnu::noinline]] int read_uninit() {
  int x;                // erroneous value
  return x;             // erroneous behaviour
}

int main() {
  scribble();
  std::printf("%d\n", read_uninit());  // GCC 16 -std=c++26 -O0: prints 0
}                                      // the same flags with -std=c++23 printed 100
```

> **Pitfall.** Zero is a valid value, not a diagnosis. GCC 16 does not warn at run time when an erroneous value is read, so a missing initializer can silently become "works by accident". Keep `-Wuninitialized` enabled, and run sanitizers in tests. Do not write code that relies on the zero, because another implementation, or a pattern flag, will pick something else.

## Old traps that are now compile errors

Several C++26 papers take patterns that were always bugs, often undefined behaviour, and make them ill-formed.

**Returning a reference to a temporary (P2748).** A `return` statement that binds the returned reference to a temporary is ill-formed by [stmt.return]. This catches the obvious `auto&& f() { return 42; }`, and also the subtle case where a conversion creates the temporary:

```cpp
const double& f() {
  static int x = 42;
  return x;          // error in C++26: binds the result to a temporary double
}
```

**Deleting an incomplete class (P3144).** `delete p` where `p` points to an incomplete class type used to compile, and was undefined behaviour if the class turned out to have a non-trivial destructor. It is now ill-formed.

**Mixed enumeration arithmetic (P2864).** C++20 deprecated arithmetic between two different enumeration types, and between an enumeration and a floating-point type. C++26 makes both ill-formed. Comparing two arrays with `==` or `<` was also deprecated in C++20, because it compared their addresses, and P2865R6 makes it ill-formed as well.

```cpp
enum Color { red };
enum Fruit { apple };

int a = red + apple;      // C++26: ill-formed (GCC 16 only warns)
double b = red * 1.5;     // C++26: ill-formed (GCC 16 only warns)
int c = red + 1;          // still fine: an unscoped enumeration with an integer
```

GCC 16 diagnoses the two enumeration cases only with a `-Wdeprecated-enum-enum-conversion` or `-Wdeprecated-enum-float-conversion` warning, not an error, which is a deviation from the draft. Clang 21 rejects them. Both compilers reject array comparison.

**The variadic comma (P3176).** `void f(int...)`, a C-style variadic function written without a comma before the ellipsis, is deprecated. Write `void f(int, ...)`. The motivation is `void g(auto...)`, which declares a function parameter pack, and `void h(auto......)`, which is a pack followed by C varargs.

**Trivial infinite loops (P2809).** This one goes the other way. A loop such as `while (true) ;`, whose body is empty and whose condition is a constant `true`, is no longer undefined behaviour under the forward-progress rules. [stmt.iter.general] treats it as repeated calls to `std::this_thread::yield`, so embedded code that spins forever on purpose is now correct.

## Smaller conveniences

**The placeholder `_` (P2169).** A variable, structured binding, init-capture, or non-static data member named `_` is *name-independent*. You can declare more than one in the same scope without a redefinition error. Using `_` after the second declaration is ill-formed, because the name is then ambiguous. Static variables and namespace-scope declarations do not get this treatment.

```cpp
#include <map>
#include <mutex>

std::mutex m;
std::map<int, int> table;

void g() {
  std::lock_guard _(m);                  // a guard you never refer to
  auto [_, inserted] = table.insert({1, 2});
  // auto x = _;                         // would be an error: _ is ambiguous here
  (void)inserted;
}
```

**Deleted with a reason (P2573).** `= delete("message")` puts a string literal in the diagnostic. GCC 16 prints, for example, "use of deleted function ...: use span instead".

**Computed `static_assert` messages (P2741).** The message of a `static_assert` may be any constant expression with `.size()` and `.data()` members, such as a `std::string_view`, or a `std::string` built during constant evaluation. It is evaluated only when the assertion fails. In practice you usually build such a message with `std::format`, which is not yet `constexpr` in GCC 16. GCC 16's `std::to_string` is not `constexpr` either.

**Structured bindings (P0963, P0609, P1061).** A structured binding declaration can be the condition of an `if`, `while`, or `switch`. The condition tests the whole hidden object, converted to `bool`, before the bindings are initialized. So `if (auto [ok, value] = parse(text))` works when `parse` returns a type with `explicit operator bool`, but `if (auto [it, ok] = m.insert(...))` is ill-formed, because a `std::pair` does not convert to `bool`. Each binding may also carry its own attributes, as in `auto [x [[maybe_unused]], y] = p;`. In templates, `auto [...xs] = t;` introduces a pack of bindings.

**`#embed` (P1967).** `#embed "file.bin"` expands to a comma-separated list of the file's bytes as integer literals, so `const unsigned char data[] = { #embed "data.bin" };` puts a binary file in your program without any generator script. `limit(n)`, `prefix(...)`, `suffix(...)`, and `if_empty(...)` parameters adjust the expansion, and `__has_embed` tests whether a resource exists.

**Pack indexing (P2662).** `Ts...[0]` names the first element of a pack. The pack-indexing topic covers it in full.

## Trivial relocation: adopted, then removed

P2786R13, trivial relocatability, was adopted in February 2025. It added the `trivially_relocatable_if_eligible` and `replaceable_if_eligible` contextual keywords and `std::trivially_relocate`. National-body comments then reported design problems, and in November 2025 P3920R0 removed the whole feature from C++26. N5050 contains none of it. Articles and compiler release notes written during 2025 may still describe it as part of C++26.

## What to remember

- Erroneous behaviour is well-defined but wrong. Implementations are encouraged to diagnose it and may terminate.
- An uninitialized local variable holds an erroneous value, and reading it is erroneous behaviour. Memory from `new` and `[[indeterminate]]` variables still have indeterminate values, so reading them is undefined behaviour.
- `[[indeterminate]]` is the explicit opt-out, and it brings back undefined behaviour if you read before writing.
- GCC 16 in C++26 mode zero-initializes automatic variables by default. Do not rely on it, and keep warnings and sanitizers on.
- Newly ill-formed in C++26: returning a reference bound to a temporary, `delete` of an incomplete class, enumeration-to-enumeration and enumeration-to-floating arithmetic, and comparisons between arrays.
- `_` can be declared repeatedly in one scope but not used once it is ambiguous. `= delete("why")` and computed `static_assert` messages improve diagnostics.
- A structured-binding condition tests the whole object, so it needs a type that converts to `bool`.
- Trivial relocation was added to C++26 and then removed again, so it is not in N5050.

## Concept Map Outline

- **Erroneous behaviour and C++26:** P2795's new category of defined-but-wrong behaviour, plus the C++26 rules that turn old traps into errors.
  - **Erroneous behaviour:** Well-defined behaviour that is always a bug and that implementations are recommended to diagnose.
    - **Not undefined:** The optimizer cannot assume it never happens; the program may be diagnosed or terminated.
    - **Never in constexpr:** An evaluation that would be erroneous is not a core constant expression.
  - **Uninitialized storage:** [basic.indet] now separates erroneous values from indeterminate ones.
    - **Automatic variables:** Start with erroneous values fixed by the implementation; reading one is erroneous behaviour.
    - **new and [[indeterminate]]:** Heap memory and opted-out variables start indeterminate; reading them is still UB.
    - **Static storage:** Static and thread-local variables are still zero-initialized.
    - **GCC 16 picks zero:** In C++26 mode, automatic variables are zero-filled unless -ftrivial-auto-var-init says otherwise.
  - **Newly ill-formed:** Patterns that were bugs, often UB, now rejected at compile time.
    - **Return to temporary:** P2748: a return that binds the result reference to a temporary is an error.
    - **delete incomplete type:** P3144: deleting a pointer to an incomplete class no longer compiles.
    - **Enum arithmetic:** P2864: enum with other enum or floating type is ill-formed; GCC 16 only warns.
    - **Array comparison:** P2865: comparing two arrays with == or < is ill-formed.
  - **New conveniences:** Small language additions aimed at clearer code and diagnostics.
    - **Placeholder _:** P2169: may be declared repeatedly in a scope, but a use after the second is ambiguous.
    - **delete with reason:** P2573: = delete("message") puts the message in the compiler's error.
    - **static_assert messages:** P2741: any constant with size() and data(), evaluated only on failure.
    - **Binding conditions:** P0963: if (auto [a, b] = e) tests the whole object converted to bool.
    - **#embed:** P1967: includes a binary file as a list of integer literals.
  - **Other changes:** Deprecations, loosened rules and a removal.
    - **Ellipsis comma:** P3176: void f(int...) is deprecated; write void f(int, ...).
    - **Trivial infinite loops:** P2809: while (true); is no longer UB; it behaves as repeated yield calls.
    - **Trivial relocation removed:** P2786 was adopted in 2025, then removed by P3920 in November 2025; not in N5050.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.scope.scope], [basic.lookup.general])

Under the C++26 draft, what happens with this function?

```cpp
int f() {
  int _ = 1;
  int _ = 2;
  return _;
}
```

A. It returns 2, because the second `_` hides the first
B. It returns 1, because the first `_` is the one that was named
C. It is ill-formed: `int _ = 2;` redefines `_`
D. It is ill-formed: the declarations are fine, but `return _;` is ambiguous

**Answer (D):** It is ill-formed: the declarations are fine, but `return _;` is ambiguous

**Why:** Since P2169, a local variable named `_` is name-independent, so a second `int _` in the same scope is not a redefinition. Once there are two such declarations, though, a use of `_` finds both, and the program is ill-formed. Declaring `_` several times is meant for objects you never refer to, such as lock guards or ignored structured bindings. A single `_` can still be used normally.

### Question 2 [warmup] ([basic.indet], [defns.erroneous], [intro.abstract])

Under the C++26 draft, what is the status of the initialization of `y`?

```cpp
void g() {
  int x;
  int y = x;
  (void)y;
}
```

A. Undefined behavior, as in C++23
B. Erroneous behavior: `x` holds an implementation-chosen erroneous value
C. Well-defined: `y` is guaranteed to be 0
D. Ill-formed: an uninitialized variable cannot be read

**Answer (B):** Erroneous behavior: `x` holds an implementation-chosen erroneous value

**Why:** In C++26 the bytes of an automatic variable without an initializer have erroneous values, and evaluating an erroneous value is erroneous behavior. That behavior is well-defined, but it is a bug that the implementation is recommended to diagnose and may terminate on. The value is fixed by the implementation, not guaranteed to be 0, although GCC 16 happens to choose 0. It is not ill-formed, because the program may never execute `g`.

### Question 3 [warmup] ([depr.ellipsis.comma], [dcl.fct])

Under the C++26 draft, what does this declaration declare?

```cpp
void f(int...);
```

A. A function template with a parameter pack of `int`s
B. Nothing: it is ill-formed in C++26
C. A C-style variadic function taking an `int` followed by `...`; the spelling without a comma is deprecated
D. A function taking a single array of `int` of unknown bound

**Answer (C):** A C-style variadic function taking an `int` followed by `...`; the spelling without a comma is deprecated

**Why:** Without a comma, `int...` is still the C-style ellipsis after one `int` parameter, exactly like `void f(int, ...)`. P3176 deprecated that spelling, so it is listed in [depr.ellipsis.comma] but remains valid. The reason is that `void g(auto...)` declares a function parameter pack, and the two forms are easy to confuse. GCC 16 and Clang 21 both warn about it in C++26 mode.

### Question 4 [tricky] ([dcl.struct.bind], [stmt.pre])

Under the C++26 draft, what happens with this code?

```cpp
#include <map>

bool add(std::map<int, int>& m) {
  if (auto [it, ok] = m.insert({1, 2}))
    return ok;
  return false;
}
```

A. It is ill-formed: the condition converts the whole `std::pair` to `bool`, and `pair` has no such conversion
B. It compiles, and the condition tests `ok`, the last binding
C. It compiles, and the condition tests `it`, the first binding
D. It is ill-formed: structured bindings cannot appear in a condition

**Answer (A):** It is ill-formed: the condition converts the whole `std::pair` to `bool`, and `pair` has no such conversion

**Why:** P0963 allows a structured binding declaration as a condition. The value tested is the hidden object that the bindings refer to, contextually converted to `bool` before the bindings are initialized. `std::pair<iterator, bool>` is not convertible to `bool`, so this is ill-formed. It works for types designed for it, such as a result type with an `explicit operator bool`. Neither binding is ever tested on its own.

### Question 5 [tricky] ([basic.indet], [dcl.attr.indet], [basic.start.static])

Under the C++26 draft, which marked read has undefined behavior rather than erroneous behavior?

```cpp
void use(int);

void h() {
  int a;
  use(a);                    // (1)
  int b [[indeterminate]];
  use(b);                    // (2)
  static int c;
  use(c);                    // (3)
}
```

A. (1)
B. (2)
C. (3)
D. None: in C++26 none of these reads has undefined behavior

**Answer (B):** (2)

**Why:** `[[indeterminate]]` opts the variable out of erroneous values, so `b` starts with an indeterminate value, and evaluating it is undefined behavior. `a` has an erroneous value, so read (1) is erroneous behavior, which is defined but a bug. `c` has static storage duration and is zero-initialized, so read (3) is correct and reads 0. Memory from `new` also still starts out indeterminate.

### Question 6 [tricky] ([stmt.return], [class.temporary], [dcl.init.ref])

Under the C++26 draft, what happens with this function?

```cpp
const double& value() {
  static int x = 42;
  return x;
}
```

A. It returns a reference to `x`, viewed as a `double`
B. It compiles, but using the result is undefined behavior
C. Its result refers to a temporary whose lifetime is extended to match the reference
D. It is ill-formed: the returned reference would be bound to a temporary

**Answer (D):** It is ill-formed: the returned reference would be bound to a temporary

**Why:** Binding a `const double&` to an `int` lvalue creates a temporary `double` holding 42.0. That temporary would die at the end of the `return`, leaving a dangling reference. Until C++23 this compiled and using the result was undefined behavior. P2748 makes a `return` statement that binds the returned reference to a temporary ill-formed, and lifetime extension never applies to a returned reference.

### Question 7 [standardese] ([expr.delete], [diff.cpp23])

Under the C++26 draft, what is the status of this translation unit?

```cpp
struct Widget;

void destroy(Widget* p) {
  delete p;
}
```

A. Well-formed, and the behavior is undefined only if `Widget` turns out to have a non-trivial destructor
B. Ill-formed
C. Well-formed, and `delete` calls `operator delete` without running a destructor
D. Ill-formed, no diagnostic required

**Answer (B):** Ill-formed

**Why:** Up to C++23, deleting a pointer to an incomplete class type was allowed, and it had undefined behavior when the complete class had a non-trivial destructor or a class-specific `operator delete`. P3144 changes [expr.delete] so that the object being deleted must not have incomplete class type, which makes the program ill-formed with a required diagnostic. GCC 16 and Clang 21 both reject it in C++26 mode.

### Question 8 [standardese] ([expr.const], [defns.erroneous], [basic.indet])

Under the C++26 draft, what is the status of the declaration of `v`?

```cpp
constexpr int f() {
  int x;
  return x;
}

constexpr int v = f();
```

A. Well-formed: `v` is initialized with the implementation's erroneous value
B. Well-formed: `v` is 0
C. Ill-formed: evaluating `f()` would read an erroneous value, so it is not a constant expression
D. Undefined behavior during compilation

**Answer (C):** Ill-formed: evaluating `f()` would read an erroneous value, so it is not a constant expression

**Why:** An expression whose evaluation would have undefined or erroneous behavior, as specified in the core language clauses, is not a core constant expression. Reading `x` evaluates an erroneous value, so `f()` cannot initialize a `constexpr` variable, and the declaration is ill-formed. The definition of erroneous behavior states this directly: a constant expression never exhibits behavior specified as erroneous. The function itself is fine, because `int x;` without an initializer is allowed in a `constexpr` function.

# Pack indexing and C++26 template features

> C++26 lets you subscript a pack, turn a structured binding into a pack, befriend a whole pack, order constraints written as folds, and pass concepts and variable templates as template arguments. Each feature removes a recursive or helper-template workaround.

- **Source:** C++ Atlas (https://cppatlas.com/topics/pack-indexing-and-cpp26-templates)
- **Track:** C++26
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [expr.prim.pack.index] (https://eel.is/c++draft/expr.prim.pack.index), [dcl.type.pack.index] (https://eel.is/c++draft/dcl.type.pack.index), [temp.variadic] (https://eel.is/c++draft/temp.variadic), [dcl.struct.bind] (https://eel.is/c++draft/dcl.struct.bind), [dcl.pre] (https://eel.is/c++draft/dcl.pre), [class.friend] (https://eel.is/c++draft/class.friend), [dcl.type.elab] (https://eel.is/c++draft/dcl.type.elab), [temp.constr.fold] (https://eel.is/c++draft/temp.constr.fold), [temp.constr.normal] (https://eel.is/c++draft/temp.constr.normal), [temp.constr.order] (https://eel.is/c++draft/temp.constr.order), [temp.param] (https://eel.is/c++draft/temp.param), [temp.arg.template] (https://eel.is/c++draft/temp.arg.template), [stmt.expand] (https://eel.is/c++draft/stmt.expand), [diff.cpp23.temp] (https://eel.is/c++draft/diff.cpp23.temp)
- **cppreference links:** [Pack indexing](https://en.cppreference.com/w/cpp/language/pack_indexing), [Pack](https://en.cppreference.com/w/cpp/language/parameter_pack), [Structured binding declaration](https://en.cppreference.com/w/cpp/language/structured_binding), [Friend declaration](https://en.cppreference.com/w/cpp/language/friend), [Constraints and concepts](https://en.cppreference.com/w/cpp/language/constraints), [Fold expressions](https://en.cppreference.com/w/cpp/language/fold), [Template parameters and template arguments](https://en.cppreference.com/w/cpp/language/template_parameters)
- **Prerequisites:** variadic-templates-and-fold-expressions, concepts-and-constraints, structured-bindings, access-control-and-friends, constexpr-in-cpp26

## The one idea

Before C++26, a pack could only be expanded as a whole. Anything else, such as taking its third element, splitting an aggregate into a pack, or befriending every type in a list, needed a recursive helper template or a `std::index_sequence` trick. The C++26 template changes all make the pack itself more useful, so the helper disappears and the intent sits in one line.

> **Mental model.** In C++26 a pack is something you can subscript, create from an object, name in a `friend` declaration, and reason about in a constraint. Each new form is still a pack expansion, so every old rule about packs (same lengths, expansion inside a template) still applies.

This is C++26. The text follows N5050, the final C++26 draft. The contracts topic records the status of the ISO ballot on that draft. The features and their papers:

| Feature | Paper | Feature-test macro | GCC 16.2 | Clang 21 |
|---|---|---|---|---|
| Pack indexing | P2662R3 | `__cpp_pack_indexing` 202311L | yes | yes |
| Structured binding packs | P1061R10 | `__cpp_structured_bindings` 202411L | yes | yes |
| Variadic friends | P2893R3 | `__cpp_variadic_friend` 202403L | yes | yes |
| Ordering of fold constraints | P2963R3 | none | no | yes |
| Concept and variable template template parameters | P2841R7 | `__cpp_template_parameters` 202502L | no | no |
| Expansion statements | P1306R5 | `__cpp_expansion_statements` 202506L | yes | no |

Every feature needs `-std=c++26`, or `-std=c++2c` on older compilers. Nothing here sits behind an extra flag. P2841 cannot be compiled with either compiler, so its examples below are checked only against the draft text.

## Pack indexing

`Ts...[N]` names the type at position `N` of a type pack, and `xs...[N]` names the element at position `N` of a value pack. The index must be a converted constant expression of type `std::size_t`, and its value must be less than the pack's length. A negative literal therefore fails as a narrowing conversion, and an index that is too large is a hard error when the template is instantiated.

```cpp
#include <cstddef>
#include <tuple>
#include <type_traits>

template<class... Ts> using First = Ts...[0];
static_assert(std::is_same_v<First<int, char>, int>);

template<int... N> constexpr int last = N...[sizeof...(N) - 1];
static_assert(last<4, 5, 6> == 6);

// The index may itself come from a pack, so the indexing expands with it.
template<std::size_t... I, class... T>
auto pick(T... xs) { return std::tuple<T...[I]...>(xs...[I]...); }
static_assert(std::is_same_v<decltype(pick<2, 0>(1, 'c', 3.0)),
                             std::tuple<double, int>>);
```

A pack-index-expression is a form of id-expression. After instantiation it is simply the name of the chosen parameter, so `decltype(xs...[0])` gives that parameter's declared type, and `decltype((xs...[0]))` gives an lvalue reference to it, exactly as with an ordinary parameter name.

Only type packs and value packs can be indexed. The operand must name a pack, so `T...[0]` with a non-pack `T` is ill-formed, and there is no syntax for indexing a pack of template template parameters.

> **Pitfall.** A pack-index-specifier is a non-deduced context. `template<class... T> void first(T...[0] x);` cannot deduce `T` from `first(1)`, because `T` is deduced as an empty pack and indexing an empty pack fails. You must write `first<int>(1)`.

Annex C records one breaking change. In C++23, `void f(T... [1]);` declared an unnamed pack of array parameters. In C++26 the same tokens are a pack index. Giving the parameter a name, as in `T... p[1]`, keeps the old meaning.

## Structured binding packs

P1061 lets one identifier in a structured binding carry an ellipsis. That identifier becomes a **structured binding pack**, holding however many elements are left after the named ones. It may appear first, last or in the middle. The pack may be empty, but the named bindings must not outnumber the elements.

```cpp
#include <cstdio>
#include <tuple>

struct C { int x, y, z; };

template<class T> void show(const T& t) {
  auto& [first, ...rest] = t;
  std::printf("%d %zu\n", first, sizeof...(rest));
}

auto product = [](auto t) { auto [...xs] = t; return (xs * ... * 1); };

int main() {
  show(C{7, 8, 9});                               // prints "7 2"
  show(std::tuple{1});                            // prints "1 0"
  std::printf("%d\n", product(std::tuple{2, 3, 4}));  // prints "24"
}
```

Two restrictions bite. A declaration may contain at most one pack. A declaration with a pack must also declare a templated entity, which means it has to sit inside a template or a generic lambda. Revision 9 allowed packs anywhere by inventing an implicit template region, but that was judged too hard to implement, and R10 removed it.

```cpp
struct C { int x, y, z; };
// int f() { auto [a, ...rest] = C{1, 2, 3}; return a; }
// error: structured binding pack outside of a template
```

> **Standardese.** [dcl.pre] says that a structured binding declaration with an sb-identifier preceded by an ellipsis "shall declare a templated entity". [dcl.struct.bind] then defines the pack's length as the structured binding size of the initializer minus the number of non-pack names.

C++26 also allows `constexpr` on a structured binding declaration (P2686R5). GCC 16 accepts `constexpr auto [a, b, c] = C{1, 2, 3};` in a function, but Clang 21 does not. GCC 16 still rejects the tuple-like case at block scope, because it would need a constexpr reference to an automatic variable, which is the part of P2686 that GCC has not yet implemented. The constexpr-in-cpp26 topic covers this in depth.

## Variadic friends

A `friend` declaration that names a type now takes a comma-separated list, and each element may be a pack expansion. That makes the passkey idiom generic.

```cpp
template<class... Ts> class Locked {
  int v = 42;
  friend Ts...;          // every type in Ts is a friend
};

struct K { template<class L> static int peek(L& l) { return l.v; } };
struct A; struct B;
class Two { friend A, B; };   // a plain list is new in C++26 as well

int demo() { Locked<K, int> l; return K::peek(l); }  // "friend int" is ignored
```

As before, a friend-type-specifier that does not designate a class type is ignored, so `Locked<K, int>` is fine. The form must be `friend Ts...;`. Writing `friend class Ts...;` is ill-formed, because [dcl.type.elab] forbids an elaborated-type-specifier whose identifier resolves to a template parameter, and that was already true of `friend class T;`.

## Ordering constraints written as folds

In C++20 and C++23, a fold expression in a constraint was a single atomic constraint. Two overloads constrained by `(std::integral<T> && ...)` and `(Num<T> && ...)` were ambiguous even when one concept clearly refined the other, because atomic constraints only subsume each other when they are the same expression.

P2963 changes normalization. A fold over `&&` or `||` whose pattern contains a pack becomes a **fold expanded constraint**. Its pattern is normalized like any other constraint, so the concepts inside it take part in subsumption.

```cpp
#include <concepts>

template<class T> concept Num = std::integral<T> || std::floating_point<T>;

template<class... T> requires (std::integral<T> && ...) int h(T...) { return 1; }
template<class... T> requires (Num<T> && ...)           int h(T...) { return 2; }

int a = h(1, 2);  // C++26 draft: 1, the integral fold subsumes the Num fold
int b = h(1.0);   // 2: only the second overload is viable
// GCC 16 does not implement P2963 and reports h(1, 2) as ambiguous.
```

One fold expanded constraint subsumes another only if both use the same fold operator, their patterns contain an equivalent unexpanded pack, and the first pattern subsumes the second. The operator rule exists because of empty packs. `(C<T> && ...)` holds for an empty pack and `(C<T> || ...)` does not, so neither may subsume the other. A pair of overloads constrained by `(std::integral<T> && ...)` and `(std::integral<T> || ...)` is still ambiguous for `k(1, 2)`.

Satisfaction short-circuits element by element, so no substitution happens after the first failing element of an `&&` fold.

> **Pitfall.** Because each element is now checked as its own atomic constraint, each must have type `bool`. In the Annex C example, `requires (T::compare(U{}) && ...)` with `compare` returning `int` was valid C++23, because the whole fold had type `bool`. It is ill-formed in C++26.

## Concepts and variable templates as template arguments

A template template parameter used to accept only class templates and alias templates. P2841 adds two new kinds. A **concept template parameter** is written `template<class> concept C`, and its argument must name a concept. A **variable template template parameter** is written `template<class> auto V`, and its argument must name a variable template. The draft now calls non-type template parameters **constant template parameters**. That renaming was done editorially alongside P2841.

```cpp
// C++26 draft only: neither GCC 16 nor Clang 21 accepts this syntax yet.
template<class T> concept Small = sizeof(T) <= 4;
template<class T> constexpr int zero = 0;

template<class T, template<class> concept Pred>
constexpr bool check = Pred<T>;

template<template<class> auto V>
constexpr int at_int = V<int>;

static_assert(check<char, Small>);
static_assert(at_int<zero> == 0);

template<typename T, template<typename> concept... CTs>
concept all_of = (CTs<T> && ...);
```

Inside the template, a concept template parameter's name is a concept-name, so it can be used in a type-constraint such as `Pred auto x`. A concept template parameter may not have associated constraints of its own. In a fold over a pack of concepts, the fold may not also expand a pack of another kind.

Subsumption has a limit here. A constraint that uses a concept template parameter whose argument is still unknown is a **concept-dependent constraint**, and a declaration whose associated constraints contain one is not eligible for subsumption. Once the concept argument is known, as in `all_of<T, A, C>`, normalization substitutes it and expands the fold into a plain conjunction, so ordering works again.

## Expansion statements

P1306 adds `template for`, which repeats its body once for each element at compile time. It accepts a brace list of expressions, a constant-size range, or anything that structured bindings can destructure. It is the natural partner to structured binding packs, and reflection relies on it heavily.

```cpp
#include <cstdio>

struct S { int i; double d; };

int main() {
  S s{1, 2.5};
  template for (auto m : s)                 // one instantiation per member
    std::printf("%zu ", sizeof(m));         // prints the size of each member
}
```

The destructuring form is defined in terms of a structured binding declaration with a pack-like list of bindings, and the enumerating form expands a brace list such as `{xs...}`. GCC 16 supports `template for` in `-std=c++26` without any extra flag. Clang 21 does not.

## What to remember

- `Ts...[N]` and `xs...[N]` index a pack. The index is a constant `std::size_t` below the pack's length, and an index pack can drive an expansion, as in `T...[I]...`.
- A pack index is a non-deduced context, and `decltype(xs...[0])` gives the parameter's declared type.
- `auto [a, ...rest] = e;` introduces a structured binding pack. Only one is allowed per declaration, and it must sit inside a template or a generic lambda.
- `friend Ts...;` and `friend A, B;` are valid in C++26. Non-class types are ignored, and `friend class Ts...;` is ill-formed.
- Folds over `&&` and `||` in constraints are fold expanded constraints. They subsume each other only with the same operator and the same pack, and each element must be a `bool` atomic constraint.
- `template<class> concept C` and `template<class> auto V` are new template template parameter kinds, and a constraint that depends on an unknown concept argument is not eligible for subsumption.
- GCC 16 lacks P2963 and P2841 and implements P2686 only in part. Clang 21 lacks P2841, P1306 and constexpr structured bindings.

## Concept Map Outline

- **C++26 template features:** Packs become indexable, creatable from objects, usable in friend lists and orderable in constraints.
  - **Pack indexing:** P2662R3: Ts...[N] picks a type and xs...[N] picks a value from a pack.
    - **Constant size_t index:** The index is a converted constant std::size_t below the pack length; out of range is ill-formed.
    - **Non-deduced context:** T...[0] as a parameter type cannot deduce T; the pack ends up empty and the call fails.
    - **decltype result:** decltype(xs...[0]) is the parameter's declared type; add parentheses for a reference.
    - **Annex C break:** void f(T... [1]) used to declare unnamed array parameters; now it is a pack index.
  - **Structured binding packs:** P1061R10: auto [a, ...rest] = e; binds the leftover elements as a pack.
    - **One pack, any position:** At most one ellipsis per declaration; it may be first, middle or last, and may be empty.
    - **Templates only:** The declaration must declare a templated entity, such as inside a template or generic lambda.
    - **constexpr bindings:** P2686 allows constexpr structured bindings; GCC 16 implements it only partially.
  - **Variadic friends:** P2893R3: friend Ts...; and friend A, B; are valid friend-type-declarations.
    - **Non-class ignored:** A friend-type-specifier that is not a class type is ignored, so int in the pack is fine.
    - **No friend class Ts...:** An elaborated-type-specifier naming a template parameter is ill-formed.
    - **Passkey idiom:** A class can grant access to a caller-supplied list of types without a helper.
  - **Fold constraints:** P2963R3: folds over && and || in constraints become fold expanded constraints.
    - **Subsumption now works:** (integral<T> && ...) is more constrained than (Num<T> && ...) when integral refines Num.
    - **Same operator, same pack:** An && fold never subsumes an || fold, because empty packs satisfy one but not the other.
    - **Bool elements:** Each element is its own atomic constraint and must be bool, which breaks some C++23 code.
    - **GCC 16 gap:** GCC 16 does not implement P2963; Clang 21 does.
  - **New template parameters:** P2841R7: concepts and variable templates can be template arguments.
    - **Concept parameter:** template<class> concept C takes a concept and may be used as a type-constraint.
    - **Variable template parameter:** template<class> auto V takes a variable template such as zero, not zero<int>.
    - **Concept-dependent constraints:** Constraints using an unknown concept argument are not eligible for subsumption.
    - **Constant template parameter:** C++26 wording renames non-type template parameters to constant template parameters.
  - **Expansion statements:** P1306R5: template for repeats its body per element at compile time.
    - **Three forms:** Enumerating over {exprs...}, iterating over a constant range, or destructuring an object.
    - **Support:** GCC 16 supports template for in -std=c++26; Clang 21 does not.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.struct.bind], [temp.variadic])

In C++26, what does this program print?

```cpp
#include <cstdio>

struct C { int x, y, z; };

template<class T> int f(T t) {
  auto [first, ...rest] = t;
  return first * 100 + sizeof...(rest);
}

int main() { std::printf("%d\n", f(C{1, 2, 3})); }
```

A. `103`
B. `101`
C. `102`
D. Nothing: a structured binding pack must be the last name in the list

**Answer (C):** `102`

**Why:** `first` binds to `x`, and the structured binding pack `rest` takes the remaining two members, so `sizeof...(rest)` is 2 and the result is `1 * 100 + 2`. `103` comes from counting every binding rather than only the pack's elements. A pack may appear anywhere in the list, not only at the end, and this declaration is inside a function template, as P1061R10 requires.

### Question 2 [warmup] ([expr.prim.pack.index], [temp.variadic], [dcl.type.decltype])

In C++26, for the call `f(1, 'c')`, what type is `R`?

```cpp
template<class... T> void f(T... xs) {
  using R = decltype(xs...[0]);
  (void)sizeof(R);
}

int main() { f(1, 'c'); }
```

A. `int&`, because `xs...[0]` is an lvalue
B. `int`
C. `int&&`
D. Ill-formed: `decltype` cannot be applied to a pack-index-expression

**Answer (B):** `int`

**Why:** A pack-index-expression is an id-expression, and its instantiation is simply the name of the selected parameter. `decltype` of an unparenthesized id-expression is the declared type of the entity, which is `int`. The `int&` answer is what `decltype((xs...[0]))` gives, because the extra parentheses make `decltype` look at the value category, which is lvalue.

### Question 3 [warmup] ([class.friend], [dcl.type.elab], [class.mem.general])

In C++26, which member declaration is ill-formed?

```cpp
struct A; struct B;

template<class... Ts> class X {
  friend Ts...;          // #1
  friend A, B;           // #2
  friend class Ts...;    // #3
};
```

A. `#1`
B. `#2`
C. `#3`
D. None of them

**Answer (C):** `#3`

**Why:** P2893R3 lets a friend-type-declaration take a list of friend-type-specifiers, each of which may be a pack expansion, so `#1` and `#2` are valid C++26. `#3` uses an elaborated-type-specifier, and [dcl.type.elab] makes `class` followed by a name that resolves to a template parameter ill-formed. That rule already rejected `friend class T;` before C++26. Write `friend Ts...;` instead.

### Question 4 [tricky] ([temp.deduct.type], [dcl.type.pack.index])

In C++26, what happens with this call?

```cpp
template<class... T> void first(T...[0] x) {}

int main() { first(1); }
```

A. `T` is deduced as `{int}` and `first<int>` is called
B. Ill-formed: no matching function, because `T` cannot be deduced from a pack-index-specifier
C. Undefined behavior: the index is out of range at run time
D. Ill-formed: a pack-index-specifier cannot be used as a parameter type

**Answer (B):** Ill-formed: no matching function, because `T` cannot be deduced from a pack-index-specifier

**Why:** A pack-index-specifier is a non-deduced context, so the argument `1` contributes nothing to deducing `T`. The trailing pack `T` is therefore deduced as empty, and substituting it makes `T...[0]` an out-of-range index, so the only candidate fails and the call has no match. Indexing cannot be undefined behavior, because the index is a constant checked at compile time. `first<int>(1)` works.

### Question 5 [tricky] ([temp.variadic], [dcl.type.pack.index], [expr.prim.pack.index])

In C++26, what is the type of `pick<2, 0>(1, 'c', 3.0)`?

```cpp
#include <cstddef>
#include <tuple>

template<std::size_t... I, class... T>
auto pick(T... xs) { return std::tuple<T...[I]...>(xs...[I]...); }

auto r = pick<2, 0>(1, 'c', 3.0);
```

A. `std::tuple<double, int>`
B. `std::tuple<int, char, double>`
C. `std::tuple<char, int>`
D. Ill-formed: `I` and `T` are expanded by the same ellipsis but have different lengths

**Answer (A):** `std::tuple<double, int>`

**Why:** In `T...[I]...` the first ellipsis is part of the pack-index-specifier, and that construct's pattern only expands `T` in place. The outer ellipsis is an ordinary pack expansion whose only unexpanded pack is `I`, so it produces `T...[2], T...[0]`, which is `double, int`. The length-mismatch answer would be right if both packs were expanded by the outer ellipsis, but `T` is consumed by the indexing.

### Question 6 [tricky] ([dcl.pre], [dcl.struct.bind])

Under the C++26 draft, is this function well-formed?

```cpp
struct C { int x, y, z; };

int f() {
  auto [a, ...rest] = C{1, 2, 3};
  return (a + ... + rest);
}
```

A. Well-formed, and it returns 6
B. Well-formed only if `f` is declared `constexpr`
C. Ill-formed: a structured binding pack can only be introduced in a templated entity
D. Ill-formed: a structured binding pack cannot follow a named binding

**Answer (C):** Ill-formed: a structured binding pack can only be introduced in a templated entity

**Why:** [dcl.pre] requires a structured binding declaration that contains a pack to declare a templated entity, and `f` is an ordinary function. An earlier revision, P1061R9, allowed this by creating an implicit template region, but that design was rejected, and R10 restricted packs to templates. Wrapping the same code in a template or a generic lambda makes it valid and returns 6.

### Question 7 [standardese] ([temp.constr.fold], [temp.constr.order], [temp.constr.normal])

Under the C++26 draft, with P2963 applied, what does `k(1, 2)` do?

```cpp
#include <concepts>

template<class... T> requires (std::integral<T> || ...)
int k(T...) { return 1; }  // #1

template<class... T> requires (std::integral<T> && ...)
int k(T...) { return 2; }  // #2

int x = k(1, 2);
```

A. Calls `#2`, because "all are integral" implies "some is integral"
B. Calls `#1`, because a disjunction is satisfied first
C. Ill-formed: fold expressions are not allowed in a requires-clause
D. The call is ambiguous

**Answer (D):** The call is ambiguous

**Why:** Both folds normalize to fold expanded constraints, and [temp.constr.order] lets one subsume the other only if they have the same fold-operator. Here the operators differ, so neither declaration is more constrained and the call is ambiguous. The implication answer fails on empty packs: `(C<T> && ...)` is satisfied for an empty pack and `(C<T> || ...)` is not, which is exactly why P2963 requires matching operators. Clang 21 reports the ambiguity. GCC 16 also does, but only because it does not implement P2963 at all.

### Question 8 [standardese] ([temp.param], [temp.arg.template])

Under the C++26 draft (P2841R7), which template argument is valid for `V`?

```cpp
template<class T> constexpr int zero = 0;
template<class T> concept Small = sizeof(T) <= 4;
template<class T> struct Box {};

template<template<class> auto V>
constexpr int at_int = V<int>;
```

A. `zero`, as in `at_int<zero>`
B. `zero<int>`, as in `at_int<zero<int>>`
C. `Small`, because a concept is a kind of variable template of type `bool`
D. `Box`, because any template whose parameter list matches is accepted

**Answer (A):** `zero`, as in `at_int<zero>`

**Why:** `template<class> auto V` is a variable template template parameter, and [temp.arg.template] says its argument must name a variable template or another variable template template parameter. `zero` is a variable template. `zero<int>` is a value, not a template. A concept is not a variable template, and it needs a concept template parameter of the form `template<class> concept C`. A class template needs a type template template parameter. No compiler available here implements P2841 yet, so this answer rests on the draft text.

# inplace_vector and the new C++26 containers

> C++26 adds inplace_vector, a vector whose capacity is fixed and whose elements live inside the object; hive, a block-based container with stable addresses; and indirect and polymorphic, which give heap-allocated objects value semantics. optional becomes a range and gains a reference specialization, and span gets at().

- **Source:** C++ Atlas (https://cppatlas.com/topics/inplace-vector-and-new-containers)
- **Track:** C++26
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [inplace.vector] (https://eel.is/c++draft/inplace.vector), [inplace.vector.overview] (https://eel.is/c++draft/inplace.vector.overview), [inplace.vector.modifiers] (https://eel.is/c++draft/inplace.vector.modifiers), [hive] (https://eel.is/c++draft/hive), [hive.overview] (https://eel.is/c++draft/hive.overview), [hive.modifiers] (https://eel.is/c++draft/hive.modifiers), [indirect] (https://eel.is/c++draft/indirect), [polymorphic] (https://eel.is/c++draft/polymorphic), [optional.iterators] (https://eel.is/c++draft/optional.iterators), [optional.optional.ref] (https://eel.is/c++draft/optional.optional.ref), [span.elem] (https://eel.is/c++draft/span.elem), [container.reqmts] (https://eel.is/c++draft/container.reqmts)
- **cppreference links:** [std::inplace_vector](https://en.cppreference.com/w/cpp/container/inplace_vector), [std::inplace_vector::try_push_back](https://en.cppreference.com/w/cpp/container/inplace_vector/try_push_back), [std::span::at](https://en.cppreference.com/w/cpp/container/span/at), [std::optional](https://en.cppreference.com/w/cpp/utility/optional), [std::optional::begin](https://en.cppreference.com/w/cpp/utility/optional/begin)
- **Prerequisites:** sequence-containers, iterator-invalidation, optional-variant-any, smart-pointers, span-and-mdspan

## The one idea

Each new type in this topic answers one question: where does the object live, and what happens to it when you copy or move the thing that owns it?

An `inplace_vector<T, N>` keeps up to `N` elements inside itself, like an `array` with a size, so it never allocates. A `hive<T>` spreads its elements over separately allocated blocks and never moves one to make room, so pointers to elements stay valid. `indirect<T>` and `polymorphic<T>` put one object on the heap but copy it deeply, so a class can hold an incomplete or polymorphic member and still behave like a value.

This is C++26. The papers are P0843R14 for `inplace_vector` (2024), P0447R28 for `hive` and P3019R14 for `indirect` and `polymorphic` (both February 2025), P3168R2 for optional range support, P2988R12 for `optional<T&>`, and P2821R5 for `span::at`. National-body comments then changed `inplace_vector` in March 2026: P3981R2 made `try_push_back` return `optional<T&>`, and P4022R0 removed `try_append_range`. Everything here follows N5050, the final C++26 draft. Its international ballot closed in October 2026 and was reported as not approved, so check the status before you quote it as published ISO C++. GCC 16's libstdc++ implements everything here except `hive`, behind `-std=c++26`, and its `inplace_vector` is not yet fully constexpr. Clang 21's libc++ has none of these types.

> **Mental model.** `inplace_vector` is "storage inside, size varies". `hive` is "storage outside, addresses never move". `indirect` and `polymorphic` are "storage outside, but copies are deep". Pick by asking who owns the bytes and what a copy means.

## inplace_vector: capacity in the type

`inplace_vector<T, N>` is a contiguous sequence container. It supports almost everything `vector` does, except the front operations: there is no `push_front`, `pop_front`, `emplace_front` or `prepend_range`. Its storage is a member, so moving one is linear in the number of elements, like `array` and unlike `vector`. The same is true of `swap`.

`capacity()` and `max_size()` are `static constexpr` and return `N`. `reserve(n)` is static too. It does nothing, except that it throws `bad_alloc` when `n > N`. `shrink_to_fit()` does nothing at all.

The headline rule is how it reports overflow. Any member function that would make the size exceed `N` throws `std::bad_alloc`, even though no allocation was attempted. That includes constructors, `resize`, `insert` and `push_back`.

```cpp
#include <cstdio>
#include <inplace_vector>
#include <new>

int main() {
  std::inplace_vector<int, 3> v{1, 2, 3};
  try {
    v.push_back(4);                       // would make size 4 > 3
  } catch (const std::bad_alloc&) {
    std::puts("full");                    // printed; v is unchanged
  }
  try {
    std::inplace_vector<int, 3> w(10);    // the constructor also throws
  } catch (const std::bad_alloc&) {
    std::puts("too big");
  }
}
```

> **Standardese.** [inplace.vector.overview] says that any member function of `inplace_vector<T, N>` that would cause the size to exceed `N` throws an exception of type `bad_alloc`. `push_back` and `emplace_back` additionally promise that if an exception is thrown there are no effects on the container.

Because the elements never relocate, `push_back` and `emplace_back` leave existing pointers and references valid. Middle insertion and erasure still shift the later elements, as in `vector`.

## Three ways to append

Throwing is right when overflow is a bug. When overflow is an expected outcome, or when exceptions are not available, two other families exist:

- `try_push_back(x)` and `try_emplace_back(args...)` append if there is room and return `optional<T&>` referring to the new element. If the vector is full they do nothing and return `nullopt`. They throw only if constructing the element throws.
- `unchecked_push_back(x)` and `unchecked_emplace_back(args...)` have the precondition `size() < capacity()`. Breaking it is undefined behavior, so use them only after you have checked.

```cpp
#include <cstdio>
#include <inplace_vector>

int main() {
  std::inplace_vector<int, 2> v;
  for (int i = 0; i < 4; ++i) {
    if (auto r = v.try_push_back(i * 10))
      std::printf("stored %d\n", *r);     // prints 0 and 10
    else
      std::printf("dropped %d\n", i * 10); // prints 20 and 30
  }
  if (v.size() < v.capacity())
    v.unchecked_push_back(99);            // not reached: v is full
}
```

In a freestanding implementation, the throwing members are deleted, while the `try_` and `unchecked_` members remain available.

> **Pitfall.** Until March 2026 the draft had `try_push_back` return `T*`, with a null pointer for failure, and it also had `try_append_range`. Older articles, and the cppreference page for `try_push_back`, still show that design. The final C++26 text returns `optional<T&>`, and `try_append_range` is gone. GCC 16 already follows the final text, and it reports `__cpp_lib_inplace_vector` as `202603L`.

## Triviality and constexpr

`inplace_vector` passes triviality through from `T`. If `T` has a trivial copy constructor, so does `inplace_vector<T, N>`. The same goes for the move constructor. If `T` is trivially destructible, so is the vector, and then it also has trivial copy and move assignment when `T` does. So `inplace_vector<int, 8>` is trivially copyable and can be copied with `memcpy`. For `N == 0`, the specialization is empty and trivially copyable whatever `T` is.

```cpp
#include <inplace_vector>
#include <string>
#include <type_traits>

static_assert(std::is_trivially_copyable_v<std::inplace_vector<int, 8>>);
static_assert(std::is_empty_v<std::inplace_vector<std::string, 0>>);
static_assert(std::inplace_vector<std::string, 5>::capacity() == 5);
```

Every member is `constexpr`, and constant evaluation also handles the overflow exception, since C++26 allows exceptions there. P0843R14 limited constant evaluation to trivially copyable, trivially default-constructible element types. P3074R7 (trivial unions, February 2025) removed that limit, and `__cpp_lib_constexpr_inplace_vector` marks the change.

```cpp
#include <inplace_vector>
#include <new>

constexpr int overflow() {
  std::inplace_vector<int, 1> v{1};
  try { v.push_back(2); } catch (const std::bad_alloc&) { return 42; }
  return 0;
}
static_assert(overflow() == 42);
```

GCC 16 does not define `__cpp_lib_constexpr_inplace_vector`. Its `inplace_vector` works at compile time only when `T` is trivial, so a `constexpr` function that builds an `inplace_vector<std::string, 3>` fails to evaluate. The topic on constexpr in C++26 covers the language side of this.

## hive: stable addresses, unordered insertion

A `hive<T, Allocator>` stores elements in a chain of separately allocated **element blocks**. Erasing an element does not move any other element. The draft only says that erased slots are found and skipped by "unspecified techniques of constant time complexity". The reference implementation, plf::colony, keeps a **skipfield** in each block that records runs of erased slots, so iteration can jump over a run in one step. It also keeps a free list of erased slots, which later insertions reuse. Blocks that become empty are freed or kept as reserved blocks. Block sizes grow by an implementation-defined factor and can be bounded with `hive_limits`.

```text
block 0 (cap 4)      block 1 (cap 8)
[ a ][ - ][ c ][ d ] [ e ][ - ][ - ][ h ][ . ][ . ][ . ][ . ]
       ^ erased             ^ skip run of 2   ^ unused capacity
iteration: a c d e h  (no element ever moved)
```

The consequences are written into the interface:

- `insert` and `emplace` take no position. The container chooses where the element goes, and a hint argument is ignored. Both are constant time.
- Insertion invalidates only the past-the-end iterator. Erasure invalidates only iterators, pointers and references to the erased elements, and also `end()` if the last element goes.
- Iterators are bidirectional, but they also support `<` and `<=>`. There is no `operator[]`.
- `hive` has no `==` or `!=`, because two hives with the same elements may hold them in different orders.
- `sort`, `unique` and `splice` are members. `get_iterator(p)` turns an element pointer back into an iterator, in time linear in the number of blocks.
- `reserve` and `trim_capacity` never invalidate anything. `shrink_to_fit`, `reshape` and `sort` may move elements and invalidate everything.

`hive` suits workloads like game entities or particle systems: lots of insertion and erasure, frequent iteration, and other structures holding pointers into the container. If you only need fast erase and don't care about order, a `vector` with swap-and-pop is often simpler. `hive` earns its place when pointers into the container must survive.

GCC 16 does not ship `<hive>`, and neither does Clang 21's libc++, so nothing in this section could be compiled here. The statements above come from the N5050 text.

## indirect and polymorphic: heap objects with value semantics

`unique_ptr<T>` is a natural way to hold a large, incomplete or polymorphic member, but it makes the enclosing class move-only and makes `const` shallow. `indirect<T>` and `polymorphic<T>`, in `<memory>`, fix both problems. Copying one copies the owned object. A `const` wrapper gives only `const` access to the owned object. Neither has a null state in normal use. The default constructor allocates and value-initializes a `T`, and the converting constructors are `explicit`.

```cpp
#include <cstdio>
#include <memory>
#include <string>

struct Node;                                   // incomplete is fine here
struct Tree { std::indirect<Node> child; };

struct Doc {
  std::indirect<std::string> text{std::string("draft")};
  void touch() const {
    // text->append("!");                      // error: *text is const here
  }
};

int main() {
  Doc a;
  Doc b = a;                                   // deep copy: a new string
  b.text->append(" v2");
  std::printf("%s / %s\n", a.text->c_str(), b.text->c_str()); // draft / draft v2
}
struct Node { int v = 0; };
```

`indirect<T>` always owns exactly a `T`. It compares and hashes by value: `==` and `<=>` compare the owned objects, and comparison with a plain `T` works too. `polymorphic<T>` may own any type `U` derived from `T`, which must be copy-constructible. Copying it copies the object as its dynamic type, so there is no slicing. It has no comparison operators and no hash.

Both types have a **valueless** state, reachable only by moving from the object. `valueless_after_move()` reports it. Dereferencing a valueless object is undefined behavior. You may assign to it or destroy it.

> **Pitfall.** After `auto q = std::move(p);`, an `indirect` is guaranteed valueless. A `polymorphic` is not. Its move constructor may either take ownership of the owned object, which leaves `p` valueless, or construct a new object from it as an rvalue, which leaves `p` holding a moved-from object. That latitude allows a small-buffer implementation. GCC 16's plain move constructor always takes ownership, but portable code must not rely on either result.

## Smaller changes: optional and span

**optional is a range** (P3168R2). `optional<T>` has `begin()` and `end()` with contiguous iterators, and `ranges::enable_view` is specialized as true, so an optional is a view of zero or one elements. A range-for over an empty optional does nothing, and an optional composes with views. Formatting optionals as ranges is explicitly disabled. Initializing or destroying the contained value invalidates the iterators.

```cpp
#include <cstdio>
#include <optional>
#include <ranges>

int main() {
  std::optional<int> o = 4;
  for (int x : o | std::views::transform([](int x) { return x * 10; }))
    std::printf("%d\n", x);                    // prints 40
  o.reset();
  for (int x : o) std::printf("%d\n", x);      // prints nothing
}
```

**optional<T&>** (P2988R12) is now a partial specialization. It holds a pointer, it is trivially copyable, and it is a borrowed range. Assignment **rebinds**: `r = b` makes `r` refer to `b`, and it never assigns through to the old referent. Construction that would bind to a temporary is deleted, so `std::optional<const int&> r = 42;` is ill-formed. `value_or` returns a value, not a reference. `optional<T&&>` is not allowed.

```cpp
#include <cstdio>
#include <optional>

int main() {
  int a = 1, b = 2;
  std::optional<int&> r = a;
  r = b;                                       // rebinds; a is untouched
  *r = 3;
  std::printf("%d %d\n", a, b);                // 1 3
}
```

**span::at** (P2821R5) throws `out_of_range` for a bad index, like the containers' `at`. `operator[]`, `front` and `back` instead have hardened preconditions, which are checked only in a hardened implementation.

P2447R6 had added a `span` constructor from `initializer_list` for C++26. In March 2026, P4144R1 removed it again, because it changed the meaning of existing code such as `span<const bool>{ptr, n}`, which picked the new constructor instead of the pointer-and-size one. It is not in N5050. GCC 16 does not provide it, but Clang 21's libc++ still does.

## What to remember

- `inplace_vector<T, N>` stores its elements inside the object and never allocates. Overflow throws `bad_alloc`, `try_push_back` returns `optional<T&>`, and `unchecked_push_back` makes overflow undefined behavior.
- `capacity`, `max_size` and `reserve` are static. Move and swap are linear, as for `array`.
- Triviality passes through from `T`, and `inplace_vector<T, 0>` is empty and trivially copyable. The draft makes everything constexpr; GCC 16 manages that only for trivial `T`.
- `hive` gives constant-time insert and erase with stable addresses. The container chooses where elements go, iterators are bidirectional, and there is no `==`. GCC 16 does not ship it.
- `indirect` and `polymorphic` are deep-copying, const-propagating owners. They become valueless only after a move. A moved-from `polymorphic` may or may not be valueless.
- `optional<T>` is a view of zero or one elements. `optional<T&>` rebinds on assignment and refuses temporaries.
- `span::at` throws. The `span` constructor from `initializer_list` was added and then removed before C++26 was finished.

## Concept Map Outline

- **C++26 containers:** inplace_vector, hive, indirect and polymorphic, plus optional as a range, optional<T&> and span::at.
  - **inplace_vector:** A contiguous sequence container with capacity N fixed in the type and elements stored inside the object (P0843R14).
    - **Overflow throws bad_alloc:** Any member that would make size exceed N throws bad_alloc; push_back then has no effects.
    - **try_push_back:** Returns optional<T&>, or nullopt when full, since P3981R2. Older sources show a T* return.
    - **unchecked_push_back:** Precondition size() < capacity(); violating it is undefined behavior.
    - **Static capacity:** capacity, max_size and reserve are static; reserve(n > N) throws bad_alloc. Move and swap are linear.
    - **Triviality passes through:** Trivial copy, move and destruction of T give the same for the vector; N == 0 is empty and trivially copyable.
    - **constexpr:** Fully constexpr in the draft since P3074R7; GCC 16 supports constant evaluation only for trivial T.
  - **hive:** Block-based container with constant-time insert and erase that never moves surviving elements (P0447R28).
    - **Unordered insertion:** insert and emplace take no position; the hint is ignored and erased slots may be reused.
    - **Stable addresses:** Insertion invalidates only end(); erasure invalidates only the erased elements.
    - **Skipfield:** The reference implementation skips runs of erased slots in O(1); the draft only says the technique is unspecified.
    - **Interface limits:** Bidirectional iterators with <=>, no operator[], no ==; sort, unique, splice and get_iterator are members.
    - **Not in GCC 16:** Neither libstdc++ 16 nor libc++ 21 ships <hive>.
  - **indirect:** Owns one heap-allocated T, copies it deeply and propagates const (P3019R14).
    - **Never null normally:** The default constructor allocates a value-initialized T; converting constructors are explicit.
    - **Value comparison:** == and <=> compare the owned objects, and work against a plain T; hash is provided.
    - **Incomplete T:** T may be incomplete where the member is declared, so it suits recursive types and pimpl.
  - **polymorphic:** Owns an object of any type derived from T and copies it as its dynamic type, so nothing is sliced.
    - **Derived and copyable:** The owned type must derive from T and be copy-constructible; there are no comparisons or hash.
    - **Valueless after move:** Moved-from indirect is valueless; moved-from polymorphic may or may not be, which permits small buffers.
  - **optional and span:** Smaller C++26 library changes to existing vocabulary types.
    - **optional is a view:** begin and end give zero or one elements with contiguous iterators (P3168R2).
    - **optional<T&>:** Holds a pointer, rebinds on assignment, refuses temporaries, and is a borrowed range (P2988R12).
    - **span::at:** Throws out_of_range for a bad index (P2821R5); operator[] has only a hardened precondition.
    - **No initializer_list span:** P2447R6 added it, and P4144R1 removed it in March 2026; libc++ 21 still ships it.

## Standardese Quiz Questions

### Question 1 [warmup] ([inplace.vector.overview], [inplace.vector.modifiers])

Under the C++26 draft, what does this program print?

```cpp
#include <cstdio>
#include <inplace_vector>
#include <new>

int main() {
  std::inplace_vector<int, 2> v{1, 2};
  if (auto r = v.try_push_back(3))
    std::puts("appended");
  else
    std::puts("full");
  try {
    v.push_back(3);
  } catch (const std::bad_alloc&) {
    std::puts("bad_alloc");
  }
  std::printf("%zu\n", v.size());
}
```

A. `appended`, `bad_alloc`, `3`
B. `full`, `bad_alloc`, `2`
C. `full`, then `std::length_error` escapes `main` and `std::terminate` is called
D. `full`, then undefined behavior, because `push_back` on a full `inplace_vector` has a precondition

**Answer (B):** `full`, `bad_alloc`, `2`

**Why:** `try_push_back` on a full vector has no effects and returns `nullopt`, so `full` is printed. `push_back` on a full `inplace_vector` throws `std::bad_alloc`, even though nothing was allocated, and it has no effects on the container, so the size is still 2. The precondition answer describes `unchecked_push_back`, which is the member whose overflow is undefined behavior. `length_error` is what `vector` throws when a request exceeds `max_size()`, but it is not what `inplace_vector` uses for exceeding its capacity.

### Question 2 [warmup] ([optional.iterators], [optional.syn])

In C++26, what does this program print?

```cpp
#include <cstdio>
#include <optional>
#include <ranges>

int main() {
  std::optional<int> o = 4;
  int sum = 0;
  for (int x : o | std::views::transform([](int x) { return x * 10; }))
    sum += x;
  o.reset();
  for (int x : o)
    sum += x;
  std::printf("%d\n", sum);
}
```

A. `40`
B. `44`
C. Nothing: it is ill-formed, because `optional` is not a range
D. Undefined behavior, because the second loop iterates an empty optional

**Answer (A):** `40`

**Why:** Since P3168R2, `optional<T>` has `begin()` and `end()`, and `ranges::enable_view` is true for it, so it is a view of zero or one elements that composes with range adaptors. The first loop sees one element, 4, transformed to 40. After `reset()`, `begin() == end()`, so the second loop runs zero times, which is well-defined. The ill-formed answer was correct in C++23.

### Question 3 [warmup] ([indirect.ctor], [indirect.relops])

In C++26, what does this program print?

```cpp
#include <cstdio>
#include <memory>
#include <string>

int main() {
  std::indirect<std::string> a(std::string("hi"));
  std::indirect<std::string> b = a;
  b->append("!");
  std::printf("%s %s %d\n", a->c_str(), b->c_str(), a == b);
}
```

A. `hi! hi! 1`
B. `hi hi! 1`
C. `hi hi! 0`
D. Nothing: `indirect` is move-only, so the copy is ill-formed

**Answer (C):** `hi hi! 0`

**Why:** Copying an `indirect` allocates a new owned object and copy-constructs it from `*a`, so `b` owns a separate string, and appending to it leaves `a` alone. `==` between two `indirect` objects compares the owned values, not the pointers, and "hi" differs from "hi!", so it yields false. The first option describes `shared_ptr`-like shallow sharing. The move-only answer describes `unique_ptr`, which is exactly what `indirect` was designed to replace for value-like members.

### Question 4 [tricky] ([optional.optional.ref], [optional.ref.ctor], [optional.ref.assign])

In C++26, what does this program print?

```cpp
#include <cstdio>
#include <optional>

int main() {
  int a = 1, b = 2;
  std::optional<int&> r = a;
  r = b;
  *r = 3;
  std::printf("%d %d\n", a, b);
}
```

A. `2 3`: the assignment writes `b` through to `a`, and `*r` still refers to `a`
B. `1 3`
C. `3 2`
D. Nothing: `optional<int&>` is ill-formed

**Answer (B):** `1 3`

**Why:** `optional<T&>` (P2988R12) holds a pointer, and its assignment rebinds rather than assigning through. `r = b` converts `b` to an `optional<int&>` and copy-assigns that pointer, so afterwards `r` refers to `b`, so `*r = 3` changes `b` and leaves `a` as 1. The first option is the assign-through semantic that was debated for years and rejected, because it would make an engaged and a disengaged optional behave differently on assignment. `optional<int&>` was ill-formed before C++26, but it is valid now.

### Question 5 [tricky] ([indirect.obs], [indirect.ctor])

In C++26, is this program well-formed?

```cpp
#include <memory>

struct Counter {
  std::indirect<int> n{0};
  void bump() const { ++*n; }
};

int main() {
  Counter c;
  c.bump();
}
```

A. Well-formed: `const` applies to the wrapper, not to the owned `int`, as with `unique_ptr`
B. Ill-formed: `std::indirect<int>` cannot be initialized with `{0}`
C. Well-formed, but undefined behavior, because it modifies an object through a const path
D. Ill-formed: in a `const` member, `*n` is a `const int&`

**Answer (D):** Ill-formed: in a `const` member, `*n` is a `const int&`

**Why:** `indirect` propagates const. Its `operator*() const` returns `const T&`, so inside a `const` member function `*n` is a `const int` lvalue, and incrementing it is ill-formed. That is the key difference from `unique_ptr<int>`, where `const` stops at the pointer and the first option would be correct. The `{0}` initializer is fine, because the `explicit` converting constructor is allowed in direct-list-initialization.

### Question 6 [tricky] ([optional.ref.ctor], [class.temporary])

In C++26, is this program well-formed?

```cpp
#include <optional>

int main() {
  std::optional<const int&> r = 42;
  (void)r;
}
```

A. Well-formed: the temporary's lifetime is extended to match `r`, as with `const int& r = 42;`
B. Well-formed, but `r` dangles at the end of the statement, so any later use is undefined behavior
C. Ill-formed: the converting constructor is defined as deleted, because it would bind to a temporary
D. Ill-formed: `optional` cannot hold a reference to `const`

**Answer (C):** Ill-formed: the converting constructor is defined as deleted, because it would bind to a temporary

**Why:** The constructor `optional<T&>(U&&)` is defined as deleted when `reference_constructs_from_temporary_v<T&, U>` is true, and binding `const int&` to the prvalue 42 creates a temporary. Lifetime extension applies only to a reference bound directly in a declaration. A reference bound inside a constructor call would dangle, which is the bug the second option describes and the deleted constructor prevents. References to `const` are allowed; `optional<const int&> r = x;` for an `int x` is fine.

### Question 7 [standardese] ([polymorphic.ctor], [indirect.ctor], [polymorphic.general])

`Shape` is a polymorphic base class and `Circle` derives from it. What does the C++26 draft guarantee about `p.valueless_after_move()` after the last line?

```cpp
#include <memory>

struct Shape { virtual ~Shape() = default; };
struct Circle : Shape { double r = 1; };

int main() {
  std::polymorphic<Shape> p(Circle{});
  std::polymorphic<Shape> q = std::move(p);
  (void)q;
}
```

A. It is `true`, as it is for `indirect`
B. It is `false`: `p` still owns a moved-from `Circle`
C. Nothing: it may be `true` or `false`
D. The question is moot, because calling any member on a moved-from `polymorphic` is undefined behavior

**Answer (C):** Nothing: it may be `true` or `false`

**Why:** The move constructor of `polymorphic` says that `*this` either takes ownership of the owned object of `other`, or owns an object of the same type constructed from it as an rvalue. It has no postcondition about `other`, unlike `indirect`'s move constructor, which promises that `other` is valueless. The latitude allows an implementation to store small objects inline. Calling `valueless_after_move()` is always allowed, so the last option is wrong. GCC 16 happens to take ownership, which gives `true`, but that is not guaranteed.

### Question 8 [standardese] ([hive.capacity], [hive.modifiers], [hive.overview])

`h` is a `std::hive<int>` with many elements, and `p` points to one of them. According to the C++26 draft, which call may invalidate `p` even though that element is not erased?

A. `h.insert(7)`
B. `h.erase(it)`, where `it` refers to a different element
C. `h.reserve(h.capacity() * 2)`
D. `h.shrink_to_fit()`
E. `h.trim_capacity()`

**Answer (D):** `h.shrink_to_fit()`

**Why:** `shrink_to_fit` may reallocate elements, and if it does, all references, pointers and iterators into the hive are invalidated and the element order may change. Insertion invalidates only the past-the-end iterator, and erasure invalidates only what refers to the erased elements, which is the whole point of `hive`. `reserve` and `trim_capacity` only add or free reserved blocks, and the draft says they leave every reference, pointer and iterator valid. `sort` and `reshape` can also invalidate, but they are not offered here.

# Hazard pointers and RCU

> C++26 adds two standard answers to the question of when a lock-free reader's object may be deleted. Hazard pointers protect individual objects and bound the garbage; RCU protects whole read-side regions and makes readers nearly free.

- **Source:** C++ Atlas (https://cppatlas.com/topics/hazard-pointers-and-rcu)
- **Track:** C++26
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [saferecl.general] (https://eel.is/c++draft/saferecl.general), [saferecl.hp.general] (https://eel.is/c++draft/saferecl.hp.general), [saferecl.hp.base] (https://eel.is/c++draft/saferecl.hp.base), [saferecl.hp.holder] (https://eel.is/c++draft/saferecl.hp.holder), [saferecl.hp.holder.mem] (https://eel.is/c++draft/saferecl.hp.holder.mem), [saferecl.rcu.general] (https://eel.is/c++draft/saferecl.rcu.general), [saferecl.rcu.base] (https://eel.is/c++draft/saferecl.rcu.base), [saferecl.rcu.domain] (https://eel.is/c++draft/saferecl.rcu.domain), [saferecl.rcu.domain.func] (https://eel.is/c++draft/saferecl.rcu.domain.func), [structure.specifications] (https://eel.is/c++draft/structure.specifications)
- **cppreference links:** [Standard library header <hazard_pointer>](https://en.cppreference.com/w/cpp/header/hazard_pointer), [Standard library header <rcu>](https://en.cppreference.com/w/cpp/header/rcu), [Concurrency support library](https://en.cppreference.com/w/cpp/thread), [std::scoped_lock](https://en.cppreference.com/w/cpp/thread/scoped_lock), [Named requirements: Lockable](https://en.cppreference.com/w/cpp/named_req/Lockable), [std::atomic<std::shared_ptr>](https://en.cppreference.com/w/cpp/memory/shared_ptr/atomic2)
- **Prerequisites:** lock-free-programming-and-aba, atomics-and-memory-ordering, mutexes-and-locks

## The one idea

A lock-free reader loads a pointer from an atomic and dereferences it. Meanwhile a writer swaps in a new object and wants to delete the old one. The writer cannot know whether some reader is still looking at it. Both C++26 facilities solve this the same way: the writer does not delete, it **retires** the object, and the library deletes it later, once no reader can still be using it. They differ in how readers announce that they are using something.

With **hazard pointers**, a reader publishes the address of each object it is about to use. Reclamation skips any retired object whose address is published. With **RCU** (read-copy update), a reader brackets its work in a **region of RCU protection**. Reclamation waits until every region that might have seen the old object has ended.

> **Mental model.** Hazard pointers say "do not free *this* object". RCU says "do not free *anything* I might have seen until I am done". The first costs a little on every protected object and keeps garbage bounded. The second costs almost nothing per read but lets one slow reader hold up every deletion.

This is C++26. Hazard pointers come from P2530R3 and RCU from P2545R4, both adopted in June 2023, which is why both feature-test macros, `__cpp_lib_hazard_pointer` and `__cpp_lib_rcu`, are `202306L`. The text here follows N5050, the final C++26 draft sent to the international ballot. That ballot was reported as not approved in October 2026, so check the status before you quote this as published ISO C++. No standard library you are likely to have ships either header yet. GCC 16's libstdc++ has neither `<hazard_pointer>` nor `<rcu>`, and libc++ 21 lists both feature-test macros as unimplemented. The reference implementations are in Meta's Folly library, whose `folly/synchronization/Hazptr.h` and RCU library provide supersets of these interfaces under their own names. The examples on this page were type-checked against a small mock of the draft interface, not against a real implementation.

## The reclamation problem in one picture

The lock-free-programming-and-aba topic shows how freeing a node too early leads both to use-after-free and to ABA, because a freed address can come back as a new node. Garbage collection would solve it, and C++ has none. Reference counting with `std::atomic<std::shared_ptr>` also solves it, but every reader then writes to a shared counter, which serializes readers on one cache line.

```text
reader                                 writer
p = src.load()        ----+
                          |            old = src.exchange(new_obj)
                          |            delete old       <- too early
p->field   <- use after free
```

Safe reclamation replaces `delete old` with `retire`, and makes the library responsible for the moment of deletion. [saferecl.general] describes the subclause as techniques that resolve exactly this access-deletion race.

## Hazard pointers: protect, then retire

A type becomes **hazard-protectable** by deriving publicly, non-virtually, and exactly once from `std::hazard_pointer_obj_base<T, D>`, where `D` is the deleter and defaults to `std::default_delete<T>`. A reader owns a `std::hazard_pointer`, obtained from `std::make_hazard_pointer()`, and calls `protect` on the atomic source.

```cpp
#include <atomic>
#include <hazard_pointer>
#include <string>

struct Config : std::hazard_pointer_obj_base<Config> {
  std::string name;
};

std::atomic<Config*> current{new Config()};

std::size_t reader() {                        // called often, in parallel
  std::hazard_pointer h = std::make_hazard_pointer();
  Config* p = h.protect(current);             // protection epoch starts
  return p->name.size();                      // *p cannot be reclaimed here
}                                             // ~hazard_pointer ends it

void writer(Config* fresh) {                  // called rarely
  Config* old = current.exchange(fresh);
  old->retire();                              // deleted once unprotected
}
```

The guarantee, informally, is that a retired object is not reclaimed while any hazard pointer has been associated with it continuously since before it was retired. The draft states this with **protection epochs**: every change of a hazard pointer's association ends one epoch and starts another, and an object only becomes *possibly-reclaimable* once every epoch that began before its retirement has ended.

Each object may be retired at most once, and the deleter must not throw. Retiring the same object twice is undefined behavior, as is calling `retire` through a base that is not part of a `T`. `retire` is `noexcept` and allocates nothing, because the deleter is stored inside the object's base. It may also perform reclamation of other objects on the spot, so a deleter that takes a lock the retiring thread already holds can deadlock.

> **Standardese.** [saferecl.hp.general] says the number of possibly-reclaimable objects "has an unspecified bound", and notes that the bound can depend on the number of hazard pointers and of retiring threads. That bound is the main thing hazard pointers buy you over RCU. The draft does not, however, say *when* reclamation happens, and C++26 has no function that forces it.

## What protect really does

`protect` is specified as a loop over `try_protect`. Written as a free function, the specification reads like this:

```cpp
#include <atomic>
#include <hazard_pointer>

template<class T>
T* protect_like(std::hazard_pointer& h, const std::atomic<T*>& src) {
  T* ptr = src.load(std::memory_order::relaxed);
  while (!h.try_protect(ptr, src)) {}   // retry until the source is stable
  return ptr;
}
```

`try_protect(ptr, src)` does four things in order. It remembers `old = ptr`, associates the hazard pointer with `*old`, reloads `ptr` from `src` with acquire ordering, and, if the value changed, clears the association. It returns whether the two values matched. The reload is the whole trick. Once the hazard pointer is published and `src` still holds the same address, any writer that removes the object must do so after the publication, so its later retirement cannot overlook it. If the value changed, the object may already be retired, and the reader must not trust it.

The `hazard_pointer` class distinguishes three states. A default-constructed or moved-from object is **empty** and owns nothing. An object from `make_hazard_pointer` owns a hazard pointer, which starts **unassociated**, and becomes **associated** after a successful `protect` or `reset_protection(p)`. `protect`, `try_protect` and `reset_protection` all have the precondition that the object is not empty.

```cpp
#include <atomic>
#include <hazard_pointer>

struct Node : std::hazard_pointer_obj_base<Node> { int value; };
std::atomic<Node*> slot{nullptr};

int peek() {
  std::hazard_pointer h;              // empty: owns no hazard pointer
  // h.protect(slot);                 // undefined behavior: precondition is !empty()
  h = std::make_hazard_pointer();     // may throw bad_alloc
  Node* p = h.protect(slot);
  int v = p ? p->value : 0;
  h.reset_protection();               // unassociated, but still owned
  return v;
}
```

> **Pitfall.** Creating a hazard pointer is the expensive part: it may allocate and may throw. P2530R3 reports about 4 ns to construct and destroy one in Folly, and under a nanosecond to protect with one that already exists. Hot loops should reuse a `hazard_pointer` and move it between objects with `reset_protection`, or hand-over-hand with two of them and `swap`. Swapping exchanges ownership without ending any protection epoch.

## RCU: regions instead of addresses

RCU readers publish nothing per object. A reader opens a region by locking an `rcu_domain`, reads whatever pointers it likes, and closes the region by unlocking. `rcu_domain` meets the *Cpp17Lockable* requirements, so the standard lock types work with it. The draft declares no constructor for it other than the deleted copy constructor, so in standard C++26 the only domain is the one returned by `std::rcu_default_domain()`. Regions nest, and `lock` and `unlock` never introduce a data race on the domain. `try_lock` is equivalent to `lock` and always returns `true`.

```cpp
#include <atomic>
#include <mutex>
#include <rcu>
#include <string>

struct Settings : std::rcu_obj_base<Settings> {
  std::string host;
};

std::atomic<Settings*> live{new Settings()};

std::string read_host() {
  std::scoped_lock region(std::rcu_default_domain());  // region of RCU protection
  return live.load(std::memory_order::acquire)->host;  // no retry, ever
}

void update(Settings* fresh) {
  Settings* old = live.exchange(fresh);
  old->retire();             // deleted after every region that might see old ends
}
```

The guarantee is in [saferecl.rcu.general]. If the evaluation that retired an object does not strongly happen before the start of a region, the end of that region strongly happens before the deleter runs. A region that started after the retirement cannot have seen the old pointer, so it does not delay anything. Readers never retry, and a reader may see either the old or the new object. That is the "copy" in read-copy update: writers build a new version and swap it in, and they never modify an object that readers can still reach.

For types you cannot change, `std::rcu_retire(p, d)` schedules `d(p)` without an intrusive base. The price is that it may allocate, and it may throw `bad_alloc` or whatever the deleter's move constructor throws. `rcu_obj_base<T, D>::retire` is `noexcept` because its deleter lives in the object. Either way, scheduled deleters may run concurrently with one another, must not throw, and each runs at most once.

## Waiting: rcu_synchronize and rcu_barrier

Two blocking functions are easy to confuse. `rcu_synchronize()` waits until every region that might already be running has ended. Formally, it waits for each region whose opening lock the call does not strongly happen before. It does not run or wait for deleters. `rcu_barrier()` waits until every deleter scheduled before the call has actually run. The draft adds a note that neither implies the other.

```cpp
#include <rcu>

struct Item : std::rcu_obj_base<Item> { int v; };

void shutdown(Item* last) {
  last->retire();
  std::rcu_synchronize();  // all old readers are gone; last may still exist
  std::rcu_barrier();      // now its deleter has run
}
```

Use `rcu_synchronize` when you want to reuse or modify the old object yourself instead of retiring it, the classic RCU update. Use `rcu_barrier` at shutdown, before destroying anything a pending deleter might touch.

> **Pitfall.** Never call `rcu_synchronize` from inside a region on the same domain. The lock that opened your region is sequenced before the call, so the call must wait for that region to close, and it never will, because the close comes after the call returns. The thread blocks forever. `rcu_barrier` inside a region has the same hazard as soon as a deleter it must wait for is held back by that region.

## Choosing between them

P2545R4 offers a rough rule: hazard pointers are a scalable replacement for reference counting, and RCU is a scalable replacement for reader-writer locking.

| Property | `atomic<shared_ptr>` | Hazard pointers | RCU |
|---|---|---|---|
| Reader cost | a shared counter write | a published address per object | almost nothing |
| Unreclaimed garbage | none | bounded | unbounded while a reader stalls |
| Reader must retry | no | if the source changed | never |
| Reclamation | immediate | deferred | deferred |
| Reader may block | yes | yes, it only pins its objects | it delays all reclamation |

Choose hazard pointers when readers hold objects for a long or unpredictable time, when you traverse a structure with a few pointers at a time, or when memory must stay bounded. Choose RCU when reads are short and frequent, when a reader touches many objects in one pass, or when updates are rare enough that holding garbage for a while is harmless. Choose neither when the data is small and reads are rare. A mutex is simpler, and simplicity is a correctness feature.

Neither facility fixes your algorithm. They only make *deletion* safe. Writers still need their own synchronization with each other, usually a mutex or a compare-and-swap, and RCU readers still need at least an acquire load to see a fully constructed object. `try_protect` performs its own acquire reload.

## What to remember

- Both facilities replace `delete` with `retire`: the library reclaims the object once no reader can still be using it.
- A hazard-protectable or rcu-protectable type has exactly one public, non-virtual base of `hazard_pointer_obj_base<T, D>` or `rcu_obj_base<T, D>`.
- `make_hazard_pointer` may allocate and throw. A default-constructed `hazard_pointer` is empty, and protecting with it is undefined behavior.
- `try_protect` publishes, reloads with acquire ordering, and clears the protection if the source changed. `protect` loops until it succeeds.
- Retiring an object twice, or a deleter that throws, is undefined behavior. Hazard pointers bound the unreclaimed garbage, and RCU does not.
- `rcu_domain` is *Cpp17Lockable*. Use `std::scoped_lock` on `rcu_default_domain()`. `try_lock` always returns `true`, and regions nest.
- `rcu_synchronize` waits for pre-existing readers, `rcu_barrier` waits for scheduled deleters, and neither implies the other. Calling either inside your own region can block forever.
- `rcu_retire` may allocate and throw, while the intrusive `retire` members are `noexcept`.
- C++26 has no custom hazard-pointer domains and no forced cleanup. GCC 16 and libc++ 21 ship neither header, and Folly is the reference implementation.

## Concept Map Outline

- **Hazard pointers and RCU:** C++26 safe reclamation: writers retire objects and the library deletes them once no reader can still use them.
  - **The reclamation problem:** A lock-free reader may still dereference an object that a writer has just unlinked.
    - **Retire, not delete:** Writers hand removed objects to the library, which picks a safe moment to call the deleter.
    - **Status:** P2530R3 and P2545R4, adopted June 2023; feature-test macros are 202306L.
    - **Implementations:** Neither libstdc++ 16 nor libc++ 21 ships the headers; Folly is the reference implementation.
  - **Hazard pointers:** A reader publishes the address it uses; reclamation skips retired objects whose address is published.
    - **hazard_pointer_obj_base:** Exactly one public non-virtual base of this type makes T hazard-protectable and stores its deleter.
    - **make_hazard_pointer:** Constructs an owned, unassociated hazard pointer; may throw bad_alloc.
    - **Empty object:** Default-constructed or moved-from; protect and reset_protection on it are undefined behavior.
    - **try_protect:** Publish, reload src with acquire, clear protection if it changed; returns whether it was stable.
    - **swap:** Exchanges ownership without ending or starting any protection epoch.
  - **Retirement rules:** What retire requires and what it does.
    - **At most once:** Retiring the same object twice is undefined behavior.
    - **Deleter must not throw:** Undefined behavior if reclaiming or a scheduled evaluation exits via an exception.
    - **Intrusive retire is noexcept:** The deleter lives in the base class, so the member retire never allocates.
    - **rcu_retire may throw:** The non-intrusive form may allocate, throwing bad_alloc; on throw nothing is scheduled.
  - **RCU:** Readers bracket work in regions; deleters run only after every region that could have seen the object ends.
    - **rcu_domain is Lockable:** Meets Cpp17Lockable, so use std::scoped_lock on rcu_default_domain().
    - **try_lock always true:** Equivalent to lock(); readers never wait for writers.
    - **Nested regions:** unlock closes the most recently opened region on that domain in the same thread.
    - **No reader retries:** A reader sees either the old or the new version and never has to start over.
  - **Waiting:** Two blocking calls with different jobs; neither implies the other.
    - **rcu_synchronize:** Blocks until every pre-existing region on the domain has ended; does not run deleters.
    - **rcu_barrier:** Blocks until every deleter scheduled before the call has been evaluated.
    - **Self-deadlock:** rcu_synchronize inside your own region waits for an unlock that comes after it, so it never returns.
    - **No hazard cleanup:** C++26 has no call that forces hazard-pointer reclamation, and no custom domains.
  - **Choosing:** Hazard pointers replace reference counts; RCU replaces reader-writer locks.
    - **Bounded garbage:** Hazard pointers bound possibly-reclaimable objects; one stalled RCU reader holds back all deletion.
    - **Reader cost:** RCU reads are almost free; hazard pointers cost a publish and reload per protected object.
    - **Writers still synchronize:** Both make deletion safe only; concurrent writers need a mutex or compare-and-swap.

## Standardese Quiz Questions

### Question 1 [warmup] ([saferecl.hp.holder.ctor], [saferecl.hp.holder.mem], [structure.specifications])

Under the C++26 draft N5050, what happens when `read()` is called?

```cpp
#include <atomic>
#include <hazard_pointer>

struct Node : std::hazard_pointer_obj_base<Node> { int value = 0; };
std::atomic<Node*> head{new Node()};

int read() {
  std::hazard_pointer h;
  Node* p = h.protect(head);
  return p->value;
}
```

A. It returns 0, and `*p` is protected until `h` is destroyed
B. `h.protect` allocates a hazard pointer on first use, then returns 0
C. Undefined behavior
D. Ill-formed: `hazard_pointer` has no default constructor

**Answer (C):** Undefined behavior

**Why:** A default-constructed `hazard_pointer` is *empty*: it owns no hazard pointer at all. `try_protect`, and therefore `protect`, has the precondition that `*this` is not empty, and violating a library precondition is undefined behavior. The default constructor does exist and is `noexcept`. You need `std::make_hazard_pointer()`, which constructs a hazard pointer and may throw `bad_alloc`; nothing allocates lazily.

### Question 2 [warmup] ([saferecl.rcu.domain.general], [saferecl.rcu.domain.members])

Under the C++26 draft N5050, what can `std::rcu_default_domain().try_lock()` return?

A. `false` while an updater is inside `rcu_synchronize`
B. Always `true`; it is equivalent to `lock()` and opens a region of RCU protection
C. `false` if the calling thread is already inside a region, because regions do not nest
D. Either value; it is unspecified

**Answer (B):** Always `true`; it is equivalent to `lock()` and opens a region of RCU protection

**Why:** `rcu_domain::try_lock` is specified as equivalent to `lock()` and returns `true`. RCU readers never wait for writers, so there is nothing for it to fail on; it exists only so that `rcu_domain` meets *Cpp17Lockable* and works with `std::scoped_lock`. Regions are explicitly allowed to nest, and `unlock` closes the most recently opened one. Because it always succeeds, the caller must eventually call `unlock`.

### Question 3 [warmup] ([saferecl.hp.general], [saferecl.hp.holder.mem], [structure.specifications])

Assuming a conforming C++26 library, is this function well-formed?

```cpp
#include <atomic>
#include <hazard_pointer>

std::atomic<int*> counter{nullptr};

int peek() {
  std::hazard_pointer h = std::make_hazard_pointer();
  int* p = h.protect(counter);
  return p ? *p : 0;
}
```

A. Well-formed: any `atomic<T*>` can be protected
B. Well-formed, but `*p` is not protected, so reading it is a data race
C. Undefined behavior when `counter` is non-null
D. Ill-formed: `int` is not a hazard-protectable type

**Answer (D):** Ill-formed: `int` is not a hazard-protectable type

**Why:** `protect` is defined in terms of `try_protect`, which *Mandates* that `T` is hazard-protectable: a class with exactly one public, non-virtual base `hazard_pointer_obj_base<T, D>`. A failed *Mandates* condition makes the program ill-formed, so this does not compile. The protection needs that base because the retired object must carry its own deleter, and only hazard-protectable objects can be retired.

### Question 4 [tricky] ([saferecl.rcu.domain.func], [saferecl.rcu.general])

Under the C++26 draft N5050, what happens when one thread calls `reader()`?

```cpp
#include <mutex>
#include <rcu>

void reader() {
  std::scoped_lock region(std::rcu_default_domain());
  // ... read RCU-protected data ...
  std::rcu_synchronize();
}
```

A. `rcu_synchronize` returns at once, because a thread never waits for its own region
B. `rcu_synchronize` waits for other threads' regions and then returns
C. `rcu_synchronize` never returns
D. Ill-formed: `rcu_synchronize` cannot be called while an `rcu_domain` is locked

**Answer (C):** `rcu_synchronize` never returns

**Why:** `rcu_synchronize` blocks until the unlock closing every region R whose opening lock the call does not strongly happen before. The lock that opened this thread's region is sequenced before the call, so the call does not strongly happen before it, and the call waits for that region to close. The closing unlock is in `region`'s destructor, which runs only after the call returns, so the thread blocks forever. There is no exemption for the calling thread's own region, and nothing makes the code ill-formed.

### Question 5 [tricky] ([saferecl.rcu.domain.func], [saferecl.rcu.general])

Under the C++26 draft N5050, which statement is guaranteed to be true when `rcu_synchronize()` returns in `retire_and_wait`?

```cpp
#include <rcu>

struct Item : std::rcu_obj_base<Item> { int v = 0; };

void retire_and_wait(Item* old) {
  old->retire();
  std::rcu_synchronize();
  // here
}
```

A. Every region of RCU protection that was open on the default domain when the call began has ended
B. `*old` has been deleted
C. `*old` has been deleted, unless a reader still holds a pointer to it
D. Every deleter scheduled before the call has run

**Answer (A):** Every region of RCU protection that was open on the default domain when the call began has ended

**Why:** `rcu_synchronize` only waits for pre-existing regions of RCU protection to close. It is not required to run or wait for any scheduled deleter, so `*old` may still exist. Waiting for scheduled evaluations is the job of `rcu_barrier`, and the draft notes explicitly that neither call implies the other. The deleter is now *allowed* to run, because no region that could have seen `old` remains, but the draft only says each scheduled evaluation runs at most once.

### Question 6 [tricky] ([saferecl.hp.holder.mem], [saferecl.hp.holder.ctor], [saferecl.hp.general])

Under the C++26 draft N5050, is `*p` still protected against reclamation on the line marked `// here`, assuming another thread may retire it at any time?

```cpp
#include <atomic>
#include <hazard_pointer>

struct Node : std::hazard_pointer_obj_base<Node> { int value = 0; };
std::atomic<Node*> head{new Node()};

int read() {
  std::hazard_pointer keep;
  Node* p;
  {
    std::hazard_pointer h = std::make_hazard_pointer();
    p = h.protect(head);
    keep.swap(h);
  }
  return p->value; // here
}
```

A. No: the protection ended when `h` was destroyed
B. Yes: `keep` now owns the hazard pointer, which is still associated with `*p`
C. No: `swap` ends the current protection epoch of both objects
D. Undefined behavior: `keep` was empty, so it cannot take part in `swap`

**Answer (B):** Yes: `keep` now owns the hazard pointer, which is still associated with `*p`

**Why:** `swap` exchanges which `hazard_pointer` object owns which hazard pointer. The draft's note says the hazard pointers themselves are unchanged and keep their associations, and no protection epoch ends or begins. After the swap, `h` is empty, so destroying it destroys nothing, while `keep` owns the hazard pointer still associated with `*p`. `swap` has no non-empty precondition, unlike `protect` and `reset_protection`.

### Question 7 [standardese] ([saferecl.hp.holder.mem])

Under N5050, `h` is non-empty and `ptr` holds a value previously loaded from `src`. Between that load and this call, another thread stores a different pointer into `src`, and nothing else changes it. After `h.try_protect(ptr, src)` returns `false`, what is the state?

A. `ptr` still holds the old value, and the hazard pointer is associated with it
B. `ptr` holds the new value of `src`, and the hazard pointer is associated with it
C. `ptr` holds the new value of `src`, and the hazard pointer owned by `h` is unassociated
D. `h` is empty, because a failed `try_protect` releases its hazard pointer

**Answer (C):** `ptr` holds the new value of `src`, and the hazard pointer owned by `h` is unassociated

**Why:** `try_protect` saves `old = ptr`, associates the hazard pointer with `*old`, assigns `src.load(memory_order::acquire)` to `ptr`, and, if `old != ptr`, calls `reset_protection()`. So on failure `ptr` is updated to the fresh value but is not yet protected, and the hazard pointer is unassociated. The fresh value is exactly what the next call needs, which is why `protect` is just a loop over `try_protect`. The object stays non-empty; only destruction or being moved from makes it empty.

### Question 8 [standardese] ([saferecl.rcu.domain.func], [saferecl.rcu.base], [saferecl.hp.base])

In the C++26 draft N5050, which of these functions may exit via an exception?

A. `rcu_obj_base<T, D>::retire`
B. `hazard_pointer_obj_base<T, D>::retire`
C. `rcu_synchronize`
D. `rcu_domain::lock`
E. `rcu_retire`

**Answer (E):** `rcu_retire`

**Why:** `rcu_retire` is the non-intrusive form: it may allocate memory to remember the pointer and a moved copy of the deleter, and it may throw `bad_alloc` or any exception from initializing that copy. If it throws, nothing is scheduled. The intrusive `retire` members are `noexcept` because the deleter is stored in the object's base class, and `rcu_synchronize`, `rcu_barrier`, `lock` and `unlock` are all `noexcept`.

# constexpr in C++26

> C++26 lets constant evaluation cast from void*, use placement new, throw and catch exceptions, bind constexpr structured bindings and construct classes with virtual bases. The rule underneath stays the same, though, because nothing may leak out of the evaluation.

- **Source:** C++ Atlas (https://cppatlas.com/topics/constexpr-in-cpp26)
- **Track:** C++26
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [expr.const.core] (https://eel.is/c++draft/expr.const.core), [expr.const.const] (https://eel.is/c++draft/expr.const.const), [expr.const.init] (https://eel.is/c++draft/expr.const.init), [dcl.constexpr] (https://eel.is/c++draft/dcl.constexpr), [dcl.pre] (https://eel.is/c++draft/dcl.pre), [dcl.struct.bind] (https://eel.is/c++draft/dcl.struct.bind), [meta.const.eval] (https://eel.is/c++draft/meta.const.eval), [propagation] (https://eel.is/c++draft/propagation), [std.exceptions] (https://eel.is/c++draft/std.exceptions), [library.c] (https://eel.is/c++draft/library.c), [basic.indet] (https://eel.is/c++draft/basic.indet)
- **cppreference links:** [Constant expressions](https://en.cppreference.com/w/cpp/language/constant_expression), [constexpr specifier](https://en.cppreference.com/w/cpp/language/constexpr), [static_assert declaration](https://en.cppreference.com/w/cpp/language/static_assert), [Structured binding declaration](https://en.cppreference.com/w/cpp/language/structured_binding), [std::is_within_lifetime](https://en.cppreference.com/w/cpp/types/is_within_lifetime), [new expression (placement new)](https://en.cppreference.com/w/cpp/language/new), [Common mathematical functions](https://en.cppreference.com/w/cpp/numeric/math)
- **Prerequisites:** constant-expressions, object-lifetime-and-storage, exceptions-and-stack-unwinding, structured-bindings

## The one idea

C++26 does not change the model of constant evaluation. It removes special cases from it. The evaluator was always an interpreter that tracks every object's type and lifetime, and it rejects anything it cannot check. Each C++26 addition is an operation the interpreter can now check: a `void*` cast back to the right type, a placement new into storage it created, or an exception that is thrown and caught before the evaluation ends.

The rule underneath is unchanged. Whatever the evaluation creates must be gone, or be safely representable, by the time it finishes. Memory from `new` must be freed, exception objects must be destroyed, and the result may not point at anything the program could not name.

This is C++26. The text here follows N5050, the final C++26 draft sent to the international ballot. That ballot closed in October 2026 and was reported as not approved, with contracts at the centre of the dispute, so check the status before you quote it as published ISO C++. GCC 16 implements most of the language parts with `-std=c++26` and differs from the draft in places noted below. Clang 21 implements fewer of them.

> **Mental model.** Constant evaluation is a sandbox with a strict exit check. C++26 adds toys to the sandbox; it does not relax the exit check.

The pre-C++26 rules, including transient allocation and `consteval`, are covered in the constant-expressions topic.

## Type erasure: void* casts and placement new

Until C++23, a cast from `void*` to an object pointer type disqualified an expression outright. That blocked type-erased code such as `std::any`-like storage and `function_ref`-like callbacks. P2738R1 allows the cast when the `void*` is null or points to an object whose type is *similar* to the target, which means the same type up to cv-qualification. Anything else is still not a constant expression, so a wrong-type cast is diagnosed instead of becoming undefined behaviour.

```cpp
constexpr int roundtrip() {
  int x = 42;
  void* p = &x;
  return *static_cast<int*>(p);      // OK since C++26: p points to an int
}
static_assert(roundtrip() == 42);

constexpr int pun() {
  int x = 42;
  void* p = &x;
  return *static_cast<short*>(p);    // not similar: not a constant expression
}
// static_assert(pun() == 42);        // error
```

Placement new followed naturally, in P2747R2. A non-allocating `new (p) T(args)` is allowed when `p` points to an object that the new `T` can *transparently replace*, roughly an object of the same type, and the storage was created within the same evaluation. In practice, that means storage from `std::allocator<T>::allocate` or a local of the same type. You can no longer construct an `int` inside an `unsigned char` buffer, and you cannot touch globals. `std::construct_at`, available since C++20, already covered most uses, but placement new now works in generic code that spells it directly. Both papers bumped `__cpp_constexpr`, and GCC 16 reports `202406L`.

```cpp
#include <memory>
#include <new>

struct S { int v; constexpr S(int x) : v(x) {} };

constexpr int build() {
  std::allocator<S> a;
  S* p = a.allocate(1);
  ::new (p) S(7);          // OK since C++26
  int r = p->v;
  p->~S();
  a.deallocate(p, 1);      // still mandatory: no leaks out of the evaluation
  return r;
}
static_assert(build() == 7);
```

> **Pitfall.** GCC 16 accepts some `void*` casts that the draft rejects. One example is casting a `void*` that points to a `Derived` back to `Base*`, and another is casting a pointer to an array's first element to a pointer to the array. Clang 21 rejects both. Write the cast back to the exact type that was erased.

## Exceptions during constant evaluation

P3068R6 removes the blanket ban on `throw`. An exception may now be thrown, unwound and caught inside a constant evaluation, provided the exception object and every copy made by `std::rethrow_exception` are destroyed before the evaluation ends. If the exception escapes, the expression is not constant, so an uncaught throw is still a compile-time error. The difference is that you can now handle it.

```cpp
#include <optional>
#include <stdexcept>

constexpr int digit(char c) {
  if (c < '0' || c > '9') throw std::invalid_argument("not a digit");
  return c - '0';
}

constexpr std::optional<int> try_digit(char c) {
  try { return digit(c); }
  catch (const std::invalid_argument&) { return std::nullopt; }
}

static_assert(try_digit('7') == 7);
static_assert(!try_digit('x'));            // caught during constant evaluation
// constexpr int bad = digit('x');         // error: exception escapes
```

The library followed. `std::exception` and its `what()`, `bad_alloc`, `bad_cast` and the other language-support exceptions became constexpr in P3068. P3378R2 did the same for the `<stdexcept>` classes and for `bad_optional_access`, `bad_variant_access` and `bad_expected_access`. So `vector::at` out of range now throws a catchable `out_of_range` at compile time. `make_exception_ptr` and `rethrow_exception` are constexpr as well, but an `exception_ptr` cannot be stored in a `constexpr` variable, because the exception object would outlive the evaluation.

Two functions were taken back. P3068 had made `std::current_exception` and `std::uncaught_exceptions` constexpr. Both depend on the program's global exception state, which a constant evaluation could observe in surprising places. P3842R2 removed `constexpr` from both before C++26 shipped, and N5050 reflects that. The rethrowing form `throw;` still works when the handled exception was created inside the evaluation.

> **Standardese.** [expr.const.core] now disqualifies "a construction of an exception object, unless the exception object and all of its implicit copies created by invocations of `std::current_exception` or `std::rethrow_exception` are destroyed within the evaluation". It also disqualifies a `dynamic_cast`, `typeid` or new-expression that would throw where no definition of the exception type is reachable.

GCC 16 implements all of this. It defines `__cpp_constexpr_exceptions` as `202411L` and `__cpp_lib_constexpr_exceptions` as `202502L`, and it already rejects `current_exception` in a constant expression. Clang 21 does not support constexpr exceptions.

## constexpr structured bindings and references to locals

P2686R5 makes two related changes. First, a structured binding declaration may be `constexpr` or `constinit`, and the specifier goes to the hidden variable `e` that holds the initializer. Second, a `constexpr` reference or pointer may refer to an automatic variable, as long as it is used inside the same function invocation. The draft calls such an object *constexpr-referenceable*. A reference that could escape, such as a `static constexpr` one or a use inside a nested lambda, is still rejected.

```cpp
#include <utility>

struct P { int x, y; };
constexpr auto [a, b] = P{1, 2};          // OK since C++26
static_assert(a + b == 3);
constexpr auto [c, d] = std::pair{3, 4};  // tuple-like, namespace scope
static_assert(c * d == 12);

void f() {
  constexpr auto [u, v] = P{5, 6};        // OK: block scope, aggregate
  static_assert(u < v);
  int x = 0;
  (void)x;
  // constexpr int& rx = x;               // OK in C++26: same function
  // static constexpr int& sx = x;        // error: could escape the invocation
}
```

The structured-binding name is treated as the member or element access on `e` that it stands for. A binding to a `mutable` member therefore cannot be read in a constant expression, even though the declaration itself is fine.

> **Pitfall.** GCC 16 implements only half of P2686. It accepts `constexpr` structured bindings for arrays and aggregates, but it still rejects `constexpr` references and pointers to automatic variables, including `constexpr const int& r = k;` where `k` is itself `constexpr`. As a result, it also rejects a block-scope `constexpr auto [p, q] = std::pair{...}`, because tuple-like bindings are references. Clang 21 implements neither part.

## Virtual bases, static_assert messages and is_within_lifetime

P3533R2 removes the rule that a class with a virtual base cannot have a constexpr constructor or destructor. In N5050, the only remaining condition for a function to be *constexpr-suitable* is that it is not a coroutine. The interpreter already knows the dynamic type of every object it creates, so a virtual base costs it nothing.

```cpp
struct Base { int v; constexpr Base(int x) : v(x) {} };
struct L : virtual Base { constexpr L() : Base(1) {} };
struct R : virtual Base { constexpr R() : Base(2) {} };
struct Diamond : L, R { constexpr Diamond() : Base(3) {} };

constexpr int share() {
  Diamond d;
  L& l = d;
  R& r = d;
  return l.v * 10 + r.v;   // one shared Base, built by Diamond
}
static_assert(share() == 33);  // C++26; GCC 16 accepts, Clang 21 rejects
```

P2741R3 lets the second argument of `static_assert` be any constant expression with `size()` and `data()` members, such as a `std::string` built at compile time, instead of only a string literal. The message is used only when the assertion fails. In that case `size()` must be a converted constant expression of type `std::size_t`, every character must be a constant, and the text is that many code units of the ordinary literal encoding. When the condition is true, the message is an unevaluated operand.

```cpp
#include <cstddef>

struct Msg {
  constexpr std::size_t size() const { return 5; }
  constexpr const char* data() const { return "hello world"; }
};
static_assert(sizeof(char) == 1, Msg{});      // passes; message unused
// static_assert(sizeof(char) == 2, Msg{});   // error: static assertion failed: hello
```

P2641R4 adds `std::is_within_lifetime(p)` to `<type_traits>`. It is `consteval`, and it returns whether `p` points to an object within its lifetime. The motivating use is asking which union member is active without reading it. An `optional<bool>`-like type can store a sentinel in a `char` member and still answer `has_value()` during constant evaluation, where reading the inactive member would be disqualified.

```cpp
#include <type_traits>

struct OptBool {
  union { bool b; char c; };
  constexpr OptBool() : c(2) {}
  constexpr OptBool(bool x) : b(x) {}
  constexpr bool has_value() const {
    if consteval { return std::is_within_lifetime(&b); }
    else { return c != 2; }   // at run time, bytes are all we have
  }
};
```

GCC 16 implements virtual bases and string-like messages, but libstdc++ 16 has no `std::is_within_lifetime`, so the last example does not compile there. Clang 21 has only the `__builtin_is_within_lifetime` builtin, which libc++ 21 does not yet wrap.

## The library catches up

N5050 marks far more of the library constexpr than C++23 did:

- **Containers and adaptors** (P3372R3): `deque`, `list`, `forward_list`, `map`, `set`, the unordered containers and their multi variants, plus `queue`, `stack` and `priority_queue`. `inplace_vector` is constexpr by design.
- **Algorithms**: `stable_sort`, `stable_partition` and `inplace_merge` (P2562R1).
- **`<cmath>`** (P1383R2): nearly everything, including `sin`, `exp`, `pow` and `sqrt`. `rint`, `nearbyint` and the rounding-mode-dependent conversions are excluded, as are `nan` and the special functions.
- **Atomics** (P3309R3): `std::atomic` and `std::atomic_ref`, which behave as ordinary objects during constant evaluation.
- **Formatting** (P3391R2): `std::format`, `format_to` and the integral `to_string` overloads, but not floating-point or pointer formatting.

For `<cmath>`, [library.c] sets the boundary. A call is a non-constant library call if it raises a floating-point exception other than `FE_INEXACT`. Rounding is fine, so `std::sqrt(2.0)` is a constant. `std::sqrt(-1.0)` raises `FE_INVALID` and `std::log(0.0)` raises `FE_DIVBYZERO`, so neither is a constant, even though both return a value at run time.

Implementations lag here. GCC 16 provides constexpr `stable_sort` and `inplace_vector`, and it has folded `<cmath>` calls as a GCC extension for years, but it defines no `__cpp_lib_constexpr_cmath`. It rejects constexpr `map`, `set`, `list`, `deque`, `unordered_map`, `priority_queue`, `atomic`, `format` and `to_string`. libc++ 21 offers constexpr `list` and `priority_queue` but not the others.

## What is still impossible

- **Escaping allocations.** `constexpr std::vector<int> v{1, 2, 3};` is still ill-formed, because the heap storage would outlive the evaluation. A `constexpr std::string` holding a short literal compiles on both libstdc++ and libc++, but only because of the small-string optimisation, which the standard does not promise.
- **Escaping exceptions**, and any `exception_ptr` that would outlive the evaluation.
- **`reinterpret_cast`**, wrong-type `void*` casts, reading an inactive union member, and `std::bit_cast` involving pointers.
- **`goto`**, `asm`, `va_arg`, `co_await` and `co_yield`, and a call to a non-constexpr function, all of which are disqualified when evaluated.
- **Undefined and erroneous behaviour.** In C++26, an uninitialized automatic variable holds an *erroneous value*, and reading it at run time is erroneous behaviour rather than undefined behaviour. In constant evaluation, erroneous behaviour disqualifies the expression just as undefined behaviour does, and the result of a constant expression may not contain an erroneous value. A variable marked `[[indeterminate]]` has an indeterminate value instead, and reading it is also rejected. The erroneous-behaviour-and-cpp26-language-changes topic covers the run-time side.

```cpp
constexpr int fine() { int x; x = 3; return x; }  // OK: written before read
static_assert(fine() == 3);
// constexpr int bad() { int x; return x; }       // erroneous read: not constant
```

> **Pitfall.** "It compiled as constexpr on my compiler" proves less than it seems. GCC folds `<cmath>` in any mode, and SSO lets short `constexpr` strings through. For portable code, check the `__cpp_lib_constexpr_*` macros, not one compiler's behaviour.

## What to remember

- The sandbox rule is unchanged. Allocations, exception objects and pointers to locals must not escape a constant evaluation.
- A `void*` may be cast back only to a type similar to the object it points to (P2738R1). Placement new is allowed into storage created by the same evaluation (P2747R2).
- `throw`, `try` and `catch` work at compile time (P3068R6), and the `<stdexcept>` types are constexpr (P3378R2). An escaping exception is still an error. `current_exception` and `uncaught_exceptions` are not constexpr (P3842R2).
- Structured bindings may be `constexpr`, and `constexpr` references may refer to locals of the same function invocation (P2686R5). GCC 16 implements only the first part.
- Constexpr constructors now work with virtual bases (P3533R2). `static_assert` accepts computed messages (P2741R3), and those messages are unevaluated when the assertion passes.
- `std::is_within_lifetime` is `consteval` and detects the active union member (P2641R4). Neither GCC 16 nor libc++ 21 ships it.
- Most of `<cmath>` is constexpr, unless the call raises a floating-point exception other than `FE_INEXACT`. Node-based containers, atomics and `format` are constexpr in the draft, but GCC 16 does not implement them yet.
- Erroneous behaviour, like undefined behaviour, disqualifies a constant expression.

## Concept Map Outline

- **constexpr in C++26:** New operations the constant evaluator can check; nothing may still escape the evaluation.
  - **Type erasure:** Operations that make any-like and function_ref-like code usable at compile time.
    - **void* cast (P2738):** Allowed back to a type similar to the pointed-to object; any other target type is not constant.
    - **Placement new (P2747):** Allowed into storage created in the same evaluation, for an object that transparently replaces the old one.
    - **Still banned:** reinterpret_cast, reading inactive union members, and bit_cast involving pointers.
  - **Exceptions (P3068):** throw, try and catch work during constant evaluation.
    - **Must be caught:** An exception that escapes the evaluation makes the expression non-constant.
    - **Library exception types:** std::exception, bad_alloc and, via P3378, logic_error, out_of_range and the bad_*_access types are constexpr.
    - **exception_ptr:** make_exception_ptr and rethrow_exception are constexpr, but an exception_ptr cannot persist in a constexpr variable.
    - **Rolled back (P3842):** current_exception and uncaught_exceptions are not constexpr in N5050.
  - **Bindings and references:** P2686 lets constexpr reach structured bindings and local objects.
    - **constexpr auto [a, b]:** constexpr and constinit apply to the hidden variable e; mutable members are still unreadable.
    - **References to locals:** constexpr int& r = x; is OK when x is an automatic variable of the same function invocation.
    - **Escape is rejected:** A static constexpr reference or a use inside a nested lambda cannot refer to the local.
    - **GCC 16 gap:** Accepts constexpr aggregate bindings but rejects constexpr references and pointers to automatics.
  - **Smaller language changes:** Three constexpr additions that each remove a long-standing workaround.
    - **Virtual bases (P3533):** Constexpr constructors and destructors may have virtual bases; only coroutines are not constexpr-suitable.
    - **static_assert messages (P2741):** Any constant with size() and data(); evaluated only when the assertion fails.
    - **is_within_lifetime (P2641):** consteval test of whether p points to a live object; finds the active union member. Not in GCC 16.
  - **Library:** Large parts of the library became constexpr in C++26.
    - **Containers (P3372):** list, deque, map, set, unordered containers and the adaptors; GCC 16 does not implement these yet.
    - **Stable algorithms (P2562):** stable_sort, stable_partition and inplace_merge are constexpr; GCC 16 supports stable_sort.
    - **cmath (P1383):** Constant unless the call raises a floating-point exception other than FE_INEXACT, so sqrt(-1.0) is not.
    - **atomic and format:** P3309 makes atomic constexpr and P3391 does the same for format and integral to_string; neither is in GCC 16.
  - **Still impossible:** The exit check and the disqualifying operations remain.
    - **Escaping allocations:** constexpr std::vector with elements is ill-formed; short strings pass only through SSO.
    - **Disqualified operations:** goto, asm, va_arg, co_await, co_yield, and calls to non-constexpr functions.
    - **Erroneous behaviour:** Reading an uninitialized local is erroneous in C++26 and, like UB, makes the expression non-constant.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.const.core], [expr.static.cast])

Under the C++26 draft, what is true of this program?

```cpp
constexpr int roundtrip() {
  int x = 42;
  void* p = &x;
  return *static_cast<int*>(p);
}

static_assert(roundtrip() == 42);

int main() {}
```

A. Ill-formed: a cast from `void*` is never allowed in a constant expression
B. Ill-formed: `static_cast` from `void*` must be written as `reinterpret_cast`
C. Well-formed: the `void*` points to an `int`, so casting it back to `int*` is allowed
D. Undefined behavior, because the type information is lost in `void*`

**Answer (C):** Well-formed: the `void*` points to an `int`, so casting it back to `int*` is allowed

**Why:** C++26 (P2738R1) allows a conversion from `void*` to an object pointer type in a constant expression when the pointer is null or points to an object whose type is similar to the target type. Here it points to an `int` and is cast to `int*`, so the assertion is a valid constant expression. The first option was the rule through C++23. A cast to an unrelated type such as `short*` is still not a constant expression, and `reinterpret_cast` is still banned outright.

### Question 2 [warmup] ([expr.const.core], [except.throw], [std.exceptions])

In C++26, is this program well-formed?

```cpp
#include <stdexcept>

constexpr int digit(char c) {
  if (c < '0' || c > '9') throw std::invalid_argument("not a digit");
  return c - '0';
}

constexpr int digit_or(char c, int fallback) {
  try { return digit(c); }
  catch (const std::invalid_argument&) { return fallback; }
}

static_assert(digit_or('x', -1) == -1);

int main() {}
```

A. Yes: the exception is thrown and caught within the constant evaluation
B. No: a throw-expression is never a core constant expression
C. No: `std::invalid_argument` is not a literal type, so it cannot be constructed at compile time
D. Yes, but only because the compiler skips the `throw` in constant evaluation

**Answer (A):** Yes: the exception is thrown and caught within the constant evaluation

**Why:** P3068R6 lets an exception be thrown and caught during constant evaluation, provided the exception object and any copies of it are destroyed before the evaluation ends. Here the handler in `digit_or` catches it, so the whole call is a constant expression with value -1. The `std::invalid_argument` objection was true before C++26, but P3378R2 made the `<stdexcept>` classes constexpr. An exception that escaped, as in `constexpr int bad = digit('x');`, would still make the initialization ill-formed.

### Question 3 [warmup] ([dcl.pre])

In C++26, what happens, and what text does the standard's recommended practice say the diagnostic should include?

```cpp
#include <cstddef>

struct Msg {
  constexpr std::size_t size() const { return 5; }
  constexpr const char* data() const { return "hello world"; }
};

static_assert(sizeof(char) == 2, Msg{});

int main() {}
```

A. Ill-formed, and the diagnostic should include `hello world`
B. Ill-formed, and the diagnostic should include `hello`
C. Ill-formed, because a `static_assert` message must be a string literal
D. Well-formed, because the message object makes the assertion non-fatal

**Answer (B):** Ill-formed, and the diagnostic should include `hello`

**Why:** `sizeof(char)` is 1 by definition, so the assertion fails and the program is ill-formed. Since C++26 (P2741R3), the message can be any constant expression with `size()` and `data()` members. Its text is the first `size()` code units starting at `data()`, which here is `hello`, not the whole null-terminated string. The string-literal-only rule held through C++23.

### Question 4 [tricky] ([dcl.constexpr], [expr.const.init])

Under the C++26 draft N5050, which of the two declarations in `f` is ill-formed?

```cpp
void f() {
  int x = 0;
  constexpr int& r = x;         // #1
  static constexpr int& s = x;  // #2
  (void)r; (void)s;
}

int main() {}
```

A. Neither
B. Only #1
C. Only #2
D. Both

**Answer (C):** Only #2

**Why:** P2686R5 made an automatic object constexpr-referenceable from points in the same function invocation, so a `constexpr` reference to the local `x` is allowed (#1). A `static` reference outlives the invocation, and the draft checks it against the nearest namespace-scope point after the declaration, where `x` is not constexpr-referenceable, so #2 is ill-formed. N5050 uses this exact pair as an example in [dcl.constexpr]. "Both" is the C++23 answer, and it is also what GCC 16 does, because GCC has not implemented this part of P2686.

### Question 5 [tricky] ([propagation], [exception.syn], [expr.const.core])

Under the C++26 draft N5050, is this program well-formed?

```cpp
#include <exception>

constexpr bool handling() {
  try {
    throw 1;
  } catch (...) {
    return std::current_exception() != nullptr;
  }
}

static_assert(handling());

int main() {}
```

A. Yes: P3068 made `std::current_exception` constexpr
B. No: a `catch (...)` handler cannot appear in a constexpr function
C. Yes, but the value of `handling()` is unspecified
D. No: `std::current_exception` is not constexpr, so calling it is not a constant expression

**Answer (D):** No: `std::current_exception` is not constexpr, so calling it is not a constant expression

**Why:** P3068 originally marked `std::current_exception` and `std::uncaught_exceptions` constexpr. Because both read global exception state, P3842R2 removed that before C++26 was finalized, and in N5050 only an exposition-only constexpr helper remains. Calling a non-constexpr function disqualifies the expression, so the `static_assert` is ill-formed. Throwing, catching and `throw;` are still fine, which is why the first option is tempting. GCC 16 rejects the call to the non-constexpr function.

### Question 6 [tricky] ([library.c], [c.math], [expr.const.core])

In C++26, on an implementation that uses IEEE 754 `double`, which of these declarations is ill-formed?

```cpp
#include <cmath>

constexpr double a = std::sqrt(2.0);
constexpr double b = std::sqrt(-1.0);

int main() {}
```

A. Neither: both calls return a value, so both are constant
B. Only `b`: it raises `FE_INVALID`
C. Only `a`: its result is inexact, so it is not a constant
D. Both: `<cmath>` functions are not constexpr

**Answer (B):** Only `b`: it raises `FE_INVALID`

**Why:** P1383R2 made most of `<cmath>` constexpr. [library.c] says a call is a non-constant library call if it raises a floating-point exception other than `FE_INEXACT`. `sqrt(2.0)` raises only `FE_INEXACT`, so `a` is fine. `sqrt(-1.0)` raises `FE_INVALID` under Annex F, so `b` is not constant-initialized, even though at run time the call would just return a NaN. The "Both" answer describes C++23, where only a small set of functions such as `fabs` were constexpr.

### Question 7 [standardese] ([dcl.pre], [expr.context])

Under the C++26 draft, is this declaration well-formed?

```cpp
#include <cstddef>

std::size_t runtime_size();

struct RT {
  std::size_t size() const { return runtime_size(); }
  const char* data() const { return "x"; }
};

static_assert(sizeof(int) >= 1, RT{});

int main() {}
```

A. Yes: the condition is true, so the message is an unevaluated operand
B. No: `size()` must be a converted constant expression
C. No: `RT` is not a literal type
D. Yes, but only if `runtime_size()` is defined

**Answer (A):** Yes: the condition is true, so the message is an unevaluated operand

**Why:** [dcl.pre] only requires that `M.size()` be implicitly convertible to `std::size_t` and that `M.data()` be implicitly convertible to `const char*`, which is true here. The constant-expression requirements on `size()` and `data()` apply only when the assertion fails. When the condition is true, the declaration has no effect and the message is an unevaluated operand, so nothing is odr-used. GCC 16 accepts the declaration. Clang 21 reports it through a warning that is an error by default, `-Winvalid-static-assert-message`, which is stricter than the draft.

### Question 8 [standardese] ([meta.const.eval], [basic.life])

Which statement about `std::is_within_lifetime` matches the C++26 draft?

A. It is `constexpr`, and at run time it inspects the object's bytes to find the active union member
B. It reads `*p` and returns `false` instead of failing if the read would be undefined
C. It is `consteval`, returns whether `p` points to an object within its lifetime, and does not read the object
D. It works for any pointer, including pointers to globals that are not usable in constant expressions

**Answer (C):** It is `consteval`, returns whether `p` points to an object within its lifetime, and does not read the object

**Why:** [meta.const.eval] declares `template<class U = void, class T> consteval bool is_within_lifetime(const T* p) noexcept`. It returns true if `p` points to an object within its lifetime, without performing a read, which is how it can detect the active member of a union. Because it is `consteval`, run-time code needs `if consteval` and a separate path. A call is ill-formed unless `p` points to an object usable in constant expressions or to one whose complete object's lifetime began within the evaluation. That rules out the last option.
