§The Annotated C++ StandardC++ 标准注疏 中文
§

The Annotated C++ Standard

C++ 标准注疏

Notes on the C++ working draft at eel.is: what the rules say, why they are written that way, how they interact, and how they got here, with examples you can run.

This site reads the C++ standard the way a language lawyer does. The clause notes follow the current working draft section by section: what each rule says, why it is written that way, and how it interacts with the rest of the standard. Every claim points at a paragraph of the draft, and every example is marked well-formed, ill-formed or undefined, ready to run on Compiler Explorer.

Around the clause notes are topic pages that follow one rule across many clauses, idioms and patterns, performance measurements, toolchain and engineering practice, the history of major features, explanations of WG21 papers, and self-graded quizzes. The site started in Chinese; every page is also available in English, and the 中文 button at the top switches between the two.

The standard, clause by clause →

Topics

How to read the C++ standardHow to find the text in the C++ standard that answers a question, understand it, cite it precisely, and how the standard changes through proposals and defect reports.Undefined behavior: the standard's view and the compiler's viewThe standard says UB is behavior for which it imposes no requirements; compilers read that as something they may assume never happens. This page uses real Clang -O2 output to show the consequences, how C++26 puts bounds on it, and how to detect and mitigate it.Value categories in practiceHow to tell whether any expression is an lvalue, xvalue or prvalue, and how value categories determine reference binding, overload resolution, decltype, move semantics and copy elision.The C++ object model: storage, objects, lifetime, pointer valuesLooking at storage, objects, lifetime and pointer values in the abstract machine separately, and using that to decide whether there is an object in a piece of memory, whether the pointer in hand points to it, and when std::launder is needed.Legal and illegal type punningWhen reading a piece of bytes as another type is legal in C++, and what problem each of strict aliasing, unions, reinterpret_cast, memcpy, std::bit_cast and std::start_lifetime_as addresses.A catalogue of dangling referencesThe many ways a reference, pointer or view can go on being used after the object it refers to has died, the standard's basis for each, whether compilers can diagnose it, and what AddressSanitizer reports.Every form of initializationWhich kind of initialization each initialization syntax performs for each category of type, what value the object gets, when it is initialized, and the most common pitfalls.Compile-time programmingWhat constexpr, consteval, constinit, if constexpr, if consteval, templates and concepts, and static reflection are each responsible for, when to use which, and why constant evaluation can catch undefined behavior for you.Order of evaluationWhether the operands of each operator are sequenced, indeterminately sequenced or unsequenced, which forms are undefined behavior as a result, and how these rules evolved from sequence points to C++17.Overload resolution walkthrough: eight classic puzzlesWorking through eight common overload resolution problems one by one in four steps, candidate set, viable set, a table of implicit conversion sequences, and tie-breakers.An overview of castsWhat implicit conversions, the four named casts, C-style and functional casts, and std::bit_cast each do, which one to pick for a given job, which kinds of type punning are legal, and the most common cast-related UB.Two-phase lookup and dependent namesWhen, from where and in what way each name in a template is looked up: non-dependent names are bound at the definition, dependent calls get additional ADL at instantiation, and modules decide which declarations are visible at instantiation.Type deduction in all its formsThe seven places in C++ where the compiler deduces a type (template argument deduction, auto, decltype, decltype(auto), CTAD, structured bindings, init-captures) actually rely on just two sets of rules; this page puts them side by side.Concepts and constraintsFrom defining a concept to overloading on constraints. The difference between requires-expressions and requires-clauses, satisfaction and subsumption of constraints, the four places to write a constraint, the hierarchy of standard library concepts, migrating from enable_if, and the most common pitfalls.The birth and death of objectsWhen the compiler declares special member functions for a class, when initialization copies, moves or does nothing at all, and how noexcept moves, trivial copyability and the order of construction and destruction show up in real programs.How C++20 coroutines workThe complete mechanism of C++20 coroutines: the three roles of promise, awaiter and handle, how co_await expands, how the compiler turns a coroutine into a state machine, why symmetric transfer is needed, and the most common lifetime mistakes.The memory model in practiceStarting from a broken piece of message-passing code, this page reasons about multithreaded programs with sequenced before, synchronizes with, happens before and modification order, using ThreadSanitizer and litmus results measured on Apple Silicon to explain what acquire/release, relaxed, seq_cst, fences and the standard library's synchronization facilities each guarantee.Lambdas and closuresWhat a lambda expression actually creates: the closure class the compiler writes for you, the rules and costs of capture, the various forms of the call operator, the ODR problems that come from closure types being unique, and dangling caused by captures.Exception safety and noexceptWhat state an object is left in when an operation throws partway through: what stack unwinding destroys, the basic, strong and nothrow guarantees and how the standard library states them, the cost of copy-and-swap, why move constructors should be noexcept, what happens when a noexcept function throws, and destructors, RAII and scope guards.Name lookup, ADL and customization pointsHow the compiler finds the declaration for a name: qualified and unqualified lookup, hiding, argument-dependent lookup and when it is turned off, hidden friends and operator lookup, and the successive generations of design the standard library has used to let users customize behavior.Pitfalls of integer and floating-point arithmeticHow built-in arithmetic quietly changes the types of its operands before computing, which out-of-range results wrap and which are UB, what the standard guarantees about floating point, and the library tools since C++20 for getting arithmetic right.Ownership and smart pointer designUsing types to express who is responsible for destroying an object: the four kinds of ownership (unique, shared, borrowed, value semantics), the costs and rules of unique_ptr, shared_ptr and weak_ptr, how to pass smart pointers as function parameters, and out_ptr, indirect, polymorphic and the most common ownership mistakes.The design of RangesThe core design decisions of the ranges library: iterator plus sentinel, the concept hierarchy, the distinction between views and containers, lazy evaluation, begin() caching, borrowing and dangling, pipelines, ranges::to and projections, and the consequences and common pitfalls each brings.Allocators and pmrStarting from one requirement, putting a vector and all of its strings into the same arena, this page covers the allocator requirements and allocator_traits, how stateful allocators propagate on copy, move assignment and swap, uses-allocator construction and scoped_allocator_adaptor, and the memory resources, performance and common pitfalls of std::pmr.Concurrency in practiceWriting real concurrent code on top of the memory model: a thread pool built from jthread, a condition variable and packaged_task that propagates exceptions and shuts down cleanly; two surprises in std::async; a bounded queue and a lock-free SPSC ring buffer; choosing a synchronization primitive; parallel algorithms and std::execution; and common mistakes such as deadlock, lost wakeups and shared_ptr races, all checked with Clang 23 and TSan.

Idioms & Patterns

RAII and scope guardsTying a resource's lifetime to an object's lifetime: which language rules guarantee that destructors run, how to write a move-only resource handle, using unique_ptr deleters and scope guards and what they cost, locks and threads in the standard library, lifetimes across coroutine suspension, and the cases RAII doesn't cover plus common traps.Pimpl and the compilation firewallHiding a class's data members behind a pointer to an incomplete type: the recompilation cascades and shared-library ABI problems it solves, where the special members of a unique_ptr implementation must be defined, const propagation, copying and the empty state after a move, C++26's std::indirect, fast pimpl, and its run-time costs and alternatives.Singletons and static initialization orderWhy the initialization and destruction order of global objects across translation units is unreliable; which part of the problem the Meyers singleton, constinit, never-destroyed singletons, nifty counters and inline variables each solve; the cost of the guard check; multiple copies of a singleton in shared libraries; and replacing singletons with dependency injection.Non-virtual interface and template methodA public non-virtual function does the checking, locking and logging, then calls a private virtual function for the customizable step. Why private virtual functions can be overridden, why access checks and default arguments both use the static type, why the template method cannot run during construction, why final does not necessarily devirtualize here, and how the standard library itself uses this structure.CRTP and static polymorphismA derived class passes itself as the template argument of its base (class D : public Base<D>): why this compiles, why static_cast<D&>(*this) is safe, how it differs from virtual functions in code generation and object size, where the standard library uses it, the common traps, and which of its uses C++23's explicit object parameters replace.MixinsBuilding a class out of several unrelated, reusable small classes through inheritance: CRTP-style mixins parameterized on the derived class and layered mixins parameterized on the base class, how constructors pass through the layers, resolving name clashes, size under the empty base optimization, the overloaded idiom, and which mixins deducing this can replace.Policy-based designSplitting a class template's behavior into several orthogonal dimensions, each provided by a template argument (a policy): how policies get into the host class, how they achieve zero overhead, policies in the standard library, constraining policies with concepts, and combinatorial explosion, type incompatibility and compile-time costs.Five ways to write a strategyExtracting the replaceable step of an algorithm and implementing the same pricing strategy with a virtual interface, std::function and its successors, a template parameter, a function pointer and std::variant; comparing ownership, run-time replaceability, size, allocation, levels of indirection, inlining and error messages, ending with a selection table.Visitors: double dispatch and std::visitAdding operations to a fixed set of types without changing them: how the classic visitor gets double dispatch from two virtual calls, the two directions of the expression problem, the acyclic visitor, the closed-set approach with std::variant and std::visit, exhaustiveness checking, multiple dispatch and how it is implemented, the indirection a recursive variant needs, and the measured costs of both approaches.Type erasure from the ground upRun-time polymorphism without a common base class and with value semantics: hand-building a Drawable step by step from an internal virtual interface, adding copying, moving, a small buffer and a hand-written vtable, explaining the rules of placement new, launder, lifetimes and noexcept moves, then looking at what each type-erasing type in the standard library erases and what it costs.Observers and callback lifetimesA subject notifies a set of observers; the hard part is not the notification but which side dies first: what raw pointer lists, unsubscribing in the destructor, weak_ptr and RAII connection objects each protect against, how reentrancy during notification and callbacks invoked under a lock go wrong, and dangling captured this in callbacks.Factories and self-registrationCreating objects by name or ID without the caller knowing the concrete type: factory functions returning unique_ptr, clone and covariant return types, a registry mapping names to creator functions, self-registration through static objects in each translation unit and why it breaks with static libraries, deferred initialization, initialization order and threads, compile-time registries, and abstract factories.Tag dispatch: from overloading to conceptsFour ways to choose an implementation at compile time from the properties of a type: iterator category tags, enable_if, if constexpr and constrained overloads; which language rule each relies on, what their error messages look like, how much extra compile time they cost, and why the standard library uses empty tag types instead of bool parameters everywhere.Expression templatesEvaluating a + b + c in one loop without temporary vectors: operators return lightweight objects that record the structure of the computation, and evaluation happens element by element on assignment. Constraining the operators with concepts, dealing with auto dangling and aliasing, and comparing with valarray, ranges' zip_transform, std::linalg and Eigen.Strong types and phantom typesUsing a class that wraps a single value to split quantities with the same representation but different meanings into different types: why typedef can't do it, the Strong<T, Tag> template and phantom tags, adding operations as needed, the conditions for zero overhead and the assembly, enum class as a strong integer, chrono::duration, std::byte and align_val_t in the standard library, unit conversions, and traps around implicit conversions, hashing and formatting.Passkey and attorney-clientA friend gets every private member at once. Passkey restricts a single public function to chosen callers, attorney-client forwards only selected private members; plus the gaps that `{}` aggregate initialization, make_shared, explicit instantiation and static reflection leave in access control.Named parameters and buildersC++ has no named arguments. How to make a call like open("f", true, false, 4096) readable: enums instead of bool parameters, option aggregates with designated initializers, method chains returning *this by reference, ref-qualifiers and explicit object parameters for temporary builders, and a few traps of default arguments.

Performance

Measuring so you can trust the resultWriting a microbenchmark whose results you can trust: why a naive timing loop measures 0 nanoseconds, which clock to use, how the inline asm of DoNotOptimize and ClobberMemory holds back the optimizer, warm-up, repetition and medians, sources of noise on macOS, common pitfalls, how to compare two versions fairly, and bench.hpp, the small harness shared by the rest of this section.Finding hot spots with a profilerFind out where the time goes before optimizing: sampling vs instrumentation, building for profiling (-O2 -g, frame pointers, why -O0 profiles can't be trusted), sample, Instruments and dtrace on macOS, perf on Linux, reading call trees, flame graphs and inlined frames, what hardware counters add, and checking the gain with Amdahl's law after fixing a hot spot.Reading compiler-generated assemblyThe minimum assembly knowledge needed to check what the compiler turned your C++ into: how to get the assembly, the AArch64 and x86-64 calling conventions, what common C++ constructs look like once compiled, and how to spot redundant calls, register spills and unvectorized loops in the assembly.What the compiler can and cannot do for youThe optimizer rewrites programs under the as-if rule and the assumption of no UB: what inlining, constant propagation, devirtualization, copy elision, dead store elimination and loop-invariant code motion each do; how aliasing, invisible functions, escaped addresses and volatile block them; and how to make Clang explain its decisions with -Rpass.Auto-vectorizationWhen the compiler rewrites a loop into SIMD instructions: the trip count must be computable, iterations must be independent, and arrays must be provably non-overlapping; why floating-point sums need the programmer's permission to reorder; how to read Clang's vectorization remarks; and what restrict, pragmas, the unseq execution policy and std::simd each tell the compiler.Link-time and profile-guided optimizationOptimization at the build level: why the compiler cannot see function bodies in another translation unit, how full LTO and ThinLTO restore inlining and devirtualization at link time and what they cost to build, PGO's instrument–merge–use steps and the code layout it changes, sampling PGO and BOLT, how much -O3 and -mcpu actually change, and two pitfalls: LTO exposing ODR violations, and stale profile data.Caches, locality and data layoutWhy the way you access memory often decides speed more than the amount of computation: measuring cache and memory latency on our test machine, comparing sequential, strided and random access, row-major vs column-major, linked lists vs vector, AoS vs SoA, padding caused by member order, prefetching, TLB and huge pages, and the effect of packing data into bits.Multithreaded performance: contention and false sharingWhy adding threads can make things slower: false sharing from cache lines bouncing between cores, contention when every thread updates the same atomic, which instructions each memory order produces on arm64 and what they cost, mutex vs spinlock vs atomic, reference-count contention when copying shared_ptr, and the overhead of starting threads and of thread pools, all measured on an M2 Pro with 1 to 12 threads.What heap allocation costsHow many nanoseconds one new/delete takes on our test machine, how to count allocations by replacing the global operator new, the allocations hidden in string, function, vector, node containers, shared_ptr and exceptions, when the compiler may delete a new/delete pair, and measurements of reuse, object pools, inline storage, aligned allocation and multithreaded allocation.Avoiding unnecessary copiesUsing a counting type and timing to find the copies and moves a program can drop: how to pass parameters, when return values are elided, where range-for, structured bindings, const, emplace, map insertion and initializer_list each make an extra copy, and why small objects are faster passed by value.Branches and branch predictionWhat conditional branches and indirect calls really cost on a modern CPU: how branch prediction works, how many nanoseconds a misprediction is worth, when the compiler removes a branch on its own, when branchless code wins and when it loses, and what likely/unlikely, PGO, virtual calls, switch and std::unreachable change in the assembly and in measurements.Moving work to compile timeWhen lookup tables, constant parameters and branches are worth computing at compile time, where the results end up in the binary, how much run time they save, and how much more you pay in compile time and size.Choosing containers: beyond complexityWhy containers with the same or better complexity are often slower: measurements on our test machine from 10 to 1 million elements of vector, deque and list; map, unordered_map, flat_map and sorted vector; reserve and bad hashes; small sets; heterogeneous lookup with string keys; per-element memory overhead; and, finally, why the real use of node containers is iterator and reference stability.

Toolchain & Engineering

From source to executableThe pipeline behind a single clang++ command: which subcommands the driver spawns, which phase of translation preprocessing, the AST, LLVM IR, assembly, object files and linking each correspond to, and how the header and module compilation models differ.Object files, symbols and linkingWhat object files contain, how C++ linkage and the ODR turn into symbol binding, COMDAT groups and weak definitions, what undefined references and duplicate definitions are in the standard, which violations the linker silently accepts, and how static libraries, shared libraries and symbol visibility behave.Name mangling (Itanium C++ ABI)How GCC and Clang encode C++ functions, variables and template specializations into symbol names the linker can compare, and how that encoding corresponds to the standard's notion of a signature.Modules in practiceHow compilers implement C++20 modules: each compiler's BMI, Clang's two compilation modes and reduced BMIs, dependency scanning, CMake's CXX_MODULES file sets, the state of import std and header units, and how module attachment shows up in symbol names.Object layout and vtables (Itanium C++ ABI)The standard specifies only a few rules about the memory layout of class objects and leaves the rest to the ABI; this page uses Clang's layout and vtable dumps to show how data members, empty bases, vptrs, vtables, thunks and virtual bases are laid out and work under the Itanium ABI.How C++ exceptions are implementedThe table-driven exception handling of the Itanium ABI that GCC and Clang use on non-Windows platforms: which runtime functions a throw calls, how two-phase unwinding finds a handler, how landing pads destroy objects and enter catch clauses, how noexcept and -fno-exceptions affect code generation, and what zero-cost really costs.Physical design: headers and dependenciesHow to organize headers and source files so that a project both compiles and compiles fast: #include as textual replacement and its cost, include guards and #pragma once, self-contained headers, what forward declarations can and can't do, inline, static and unnamed namespaces in headers, explicit instantiation of templates, the dependency graph, cyclic dependencies and levelization, and modules as the way out.Build speedHow to measure and shorten C++ build times: -ftime-trace to see where the time goes, the split between frontend and backend, the cost of standard headers and template instantiation, and how much precompiled headers, import std, extern template, unity builds, parallel builds, compiler caches, linkers, debug info and LTO each save or cost.Library boundaries: static libraries, shared libraries and ABIWhat makes up the boundary of a C++ library: what static and shared libraries contain, controlling exported symbols with visibility, which changes break binary compatibility without changing any symbol name, why a C interface is the most stable boundary, how exceptions and RTTI cross shared libraries, who allocates and who frees, and how install names, sonames and inline namespaces manage versions.Organizing a project with CMakeTarget-centric CMake: a library, an executable and tests; PRIVATE/PUBLIC/INTERFACE usage requirements; which compiler options the language standard and build type finally turn into; warnings, sanitizer presets, compile_commands.json; installing and exporting a library; building modules; and common anti-patterns.Managing dependenciesHow to bring third-party libraries into a C++ project: why there is no common package format and why compile options must match, how two versions of the same library in one program cause an ODR violation, how system packages, FetchContent, vcpkg, Conan, submodules and vendoring each work, and pinning versions, verifying hashes and choosing by project type.Choosing an error-handling strategyHow a project reports and handles errors: first tell program bugs, recoverable environmental failures and exceptional situations apart, then choose between exceptions, error_code, std::expected and return codes, and deal with module boundaries, -fno-exceptions, error context, nodiscard, assertions, standard library hardening and contracts.Designing and evolving APIsHow to design C++ interfaces that are hard to misuse and can evolve: parameter and return types that express ownership and nullability, const and ref-qualifiers, making illegal states unrepresentable, nodiscard, deprecated and noexcept as part of the contract, the overload-set and ADL risks library authors face, and changing an interface without breaking users, giving users feature-test macros, and documenting preconditions.Testing, sanitizers and fuzzingHow to test C++ code so that UB and data races get caught: a minimal test framework, compile-time tests and compile-failure tests, what ASan, LSan, UBSan and TSan each catch, what they cost and which can't be combined, standard library hardening in tests, a CI build matrix, fuzzing with libFuzzer, property-based testing, coverage with llvm-cov, and the same tests giving different results at -O0 and -O2.Compiler warnings and static analysisFinding defects before running: what the standard requires compilers to diagnose and what it doesn't, which warnings -Wall, -Wextra and -pedantic actually enable, a recommended set of warning options and the errors each catches, -Werror and third-party headers, lifetime and thread-safety annotations, using clang-tidy, the Clang static analyzer and clang-format, and what static analysis can't do.Debugging C++ programsDebugging C++ with lldb on macOS: where debug info comes from, how optimization levels affect stepping and variables, breakpoints, conditional breakpoints, exception breakpoints and watchpoints, inspecting STL containers, reading crash call stacks and core files, using ASan reports as debugging clues, C++26's <debugging>, and printing types and tracing values at compile time and run time.Reading compiler errorsWhat a Clang diagnostic is made of, how to read candidate lists and instantiation chains, which language rule each of a dozen or so of the most common and most puzzling compile and link errors corresponds to and how to fix it, and the compiler options that control diagnostic output.

History

A short history of C++ standardization: from Cfront to C++26How C++ went from a compiler that translated into C to an ISO standard, why C++0x took more than a decade, what the three-year release train left in today's language, and how a proposal becomes standard wording.Thirty years of conceptsWhy templates went so long without interfaces, why C++0x concepts were pulled in 2009, and what design C++20 adopted instead; today's rules for satisfaction, subsumption and `Concept auto` are what those trade-offs left behind.From pthreads to C++26: threads and the memory modelHow C++ went from a language that didn't know threads existed to one whose standard defines data races and memory orders; why it chose sequential consistency for data-race-free programs, why consume and out-of-thin-air values were never solved well, and which debates produced the destructor behavior of thread, async and jthread.A decade of executors: from executors to std::executionWhy C++26's std::execution has no executor but has senders, receivers, operation states and schedulers; how the flaws of early executor designs shaped today's [exec] step by step, and why networking did not make it into the standard as a result.Coroutines: from Simula to C++20/26Why C++20 chose stackless coroutines, why the keywords have a co_ prefix, why allocating the frame is only something an implementation "may need" to do, and why the standard library's coroutine types only arrived in C++23 and C++26.Template metaprogramming: from accidental Turing completeness to static reflectionTemplates were designed only for containers and algorithms, yet turned out by accident to be a compile-time language; from C++11 on, the language took over its uses one by one with constexpr, variadic templates, if constexpr, concepts and static reflection, and traces of the old techniques remain in the rules today.constexpr: fifteen years of growing compile-time evaluationFrom C++98's integral constant expressions and template metaprogramming, to C++11 constexpr functions limited to a single return, to C++20's compile-time vector, consteval and constinit, and C++26's compile-time exceptions; what each step relaxed, why, and which limits never moved.The STL and the birth of the C++98 standard libraryWhy containers before templates were awkward, how the STL used iterators to separate containers from algorithms, and how 1990s decisions about allocators, char_traits, copy-on-write strings, vector<bool> and auto_ptr remain in today's wording.From Boost and TR1 to C++26: how the standard library grewHow the standard library grew after C++98: where its components came from, which designs patch older ones, why ABI compatibility makes existing components so hard to change, and the debate over whether the standard library should keep getting bigger.How move semantics and value categories came aboutWhy rvalue references can't bind to lvalues, why a class with a destructor gets no implicit move operations, where names like xvalue come from, why C++17 changed what a prvalue means, and why the rules for when return x; moves changed four times; from the copying problem of C++98 to C++26.Where modules came fromWhy C++20 modules don't export macros, why there are both a global module fragment and header units, and why module and import are preprocessing directives; these rules come from several competing designs over more than a decade, and from concessions made to build tools.Contracts: pulled from C++20, back in C++26Why C++ contracts were pulled out of C++20 entirely in 2019, how the C++26 redesign answers the old disagreements, and the problems that are still open.

Papers

How to read a proposalHow to read the numbers and revisions of WG21 proposals and where to find them, what parts a proposal is made of, how to map its wording changes onto the current draft, and how to tell whether it finally entered the standard as a new feature or as a defect fix.Guaranteed copy elision (P0135)How C++17 lets types that can be neither copied nor moved be returned by value from factory functions. P0135 did not change copy elision from permitted to required; it redefined prvalues so that, until materialized, a prvalue is not an object at all.Implicit object creation (P0593)C++20, as a defect fix, specifies that operations like malloc, operator new and memcpy create objects on demand, giving C-style low-level code defined behavior. This page covers the problem it solves, the rejected alternatives, the final wording, and why std::start_lifetime_as was still needed afterwards.Rewriting declarations and lookup (P1787)C++23's P1787R6 rewrote the wording for scopes and name lookup. What was wrong with the old wording, which concepts the new wording introduced, which behaviors actually changed and which rules were merely spelled out, and how compilers implement it today.Explicit object parameters (P0847)C++23 lets a member function write the object it is called on as a first parameter marked with this, so the object's type, constness and value category can be deduced. The duplicated code it targets, the syntaxes and lookup rules the proposal compared, why the final design gives the body no this, makes taking the address yield an ordinary function pointer and forbids virtual, the hidden problems of deducing a derived type, and how the standard library uses it.Simpler implicit move (P1825, P2266)When return x; moves instead of copying. From C++11's two-stage overload resolution borrowed from the copy elision conditions, through the gradual relaxations of CWG1579 and P1825, to C++23's P2266 making the returned name an xvalue outright, and which code changed meaning at each step.Fixing temporaries in range-based for (P2718)C++23 keeps every temporary in a range-based for initializer alive until the loop ends. Why the fix took thirteen years, which alternatives the committee weighed, what the final wording changed, and which dangling cases it still leaves behind.Class types as template parameters (P0732, P1907)How C++20 let class types and floating-point numbers become constant template parameters. The first design used the defaulted <=> to decide whether two arguments are the same; after a series of inconsistencies came to light it was replaced by member-wise structural types, and that choice is behind today's rules for fixed_string, -0.0 and private members.Static reflection (P2996)C++26 lets a program query types, members and enumerators at compile time as std::meta::info values, and splice them back into code with [: :]. Why it chose a single opaque value-based type, why the token is ^^, how access control and error handling were settled, and which capabilities were deferred.Contracts (P2900)How P2900 made preconditions, postconditions and assertions part of the language. Why pre/post/contract_assert rather than attribute syntax or assert; why whether to check is left to the build instead of written on each assertion; why predicates are treated as const and may be evaluated zero or more times; and the gaps the minimum viable product leaves on purpose, along with the objections that remain.std::execution (P2300)Why C++26's sender/receiver model replaced futures, coroutines and executors as the foundation of standard asynchrony. What laziness, three completion channels, allocation-free connect/start, stop tokens, structured concurrency and member-function customization each solve, and what each costs.Erroneous behavior and uninitialized reads (P2795)How C++26 deals with reading uninitialized local variables, a common security hole. Why zero-initializing everything was not adopted and a new category of behavior, erroneous behavior, was added instead, so that uninitialized automatic variables hold an erroneous value chosen by the implementation, with [[indeterminate]] as the escape hatch for performance-sensitive code; and how far Clang 23 is from these semantics today.Trivial relocation (P2786 and P1144)When moving an object to new memory, can a single memcpy replace a move construction plus destruction? The library practice of twenty years, where the two competing proposals disagreed on assignment semantics, explicit declarations and whether memcpy is enough, how P2786 entered C++26 and was then removed, and what libc++ already does today when growing a vector.Exceptions at compile time (P3068)C++26 lets constant evaluation throw and catch exceptions, as long as the exception object is destroyed within the same evaluation. Why compile-time code used to need two error paths, what the alternatives were, how the wording changes only two items in [expr.const], how the library's exception types followed, and why uncaught_exceptions and current_exception had their constexpr withdrawn again.Pack indexing (P2662)C++26 uses Ts...[N] and args...[N] to get the Nth type or element of a pack directly. How much compile time the earlier recursive templates, detours through tuple and inheritance-based deduction cost, why the syntaxes and library approaches the proposal compared lost out, why negative indices and deduction were excluded, and how unnamed T...[n] parameters change meaning as a result.mdspan (P0009)C++23's std::mdspan is a multidimensional view over a block of memory, made of three parts: shape, layout and accessor. The older idioms it replaces, the layout problem it inherited from Kokkos, why the shape is written as extents rather than an array type, why there are exactly two customization policies, why m[i, j] required a language change first, why it is not a range, and C++26's submdspan and padded layouts.std::format and std::print (P0645, P2093, P2286)How C++20's std::format and C++23's std::print avoid the drawbacks of both printf and iostream: Python-style format strings, locale independence by default, extension by specializing formatter, and type erasure to control code size. Why compile-time checking of format strings is done with a consteval constructor and why that counted as a breaking change; how print handles Unicode on the Windows console; how ranges are output by default; and how runtime format strings evolved from vformat to dynamic_format.ranges::to and constructing containers from ranges (P1206)C++20 views had no way back to containers, so P1206 added ranges::to plus from_range constructors and *_range members to every standard container. Why it ended up as a free function plus a tag, why the four construction methods are tried in this order, and the later fixes and C++26's reserve_hint.std::generator (P2502)C++20 had coroutines but no coroutine types, so everyone wrote their own generators. How C++23's std::generator decided that its first template argument is the reference type, that it yields T&& by default, and that co_yield of an lvalue copies; why recursive generation uses one type and one active stack; why the allocator is passed in as a parameter; and why it is only a single-pass, move-only view.Standard library hardening (P3471)How C++26 turns library UB such as vector out-of-bounds access or dereferencing an empty optional into guaranteed termination. A subset of existing preconditions is marked as hardened preconditions, and whether a hardened implementation is provided is implementation-defined. Why only cheap bounds checks were chosen, why the contract violation mechanism was borrowed, and why the observe semantic was later excluded.

Quizzes

Exam 1 · Object model and lifetime25 questions on where objects come from, when lifetime begins and ends, whether old names still work after storage is reused, how long temporaries live, and through which glvalue types an object may be read or written. Every question comes with a verdict and paragraph references into the current draft.Exam 2 · Initialization, value categories and references25 questions on where default-, value- and zero-initialization part ways, list-initialization and narrowing, how the aggregate rules changed between standards, copy- versus direct-initialization, reference binding, value categories and decltype, guaranteed copy elision, implicit move, and C++26 erroneous behavior and static initialization.Exam 3 · Name lookup, overload resolution and access control25 questions on scopes and hiding, unqualified and qualified lookup, ADL and hidden friends, using-declarations and using-directives, member lookup under multiple inheritance, the ranking and tie-breaker rules of overload resolution, C++20's rewritten comparison operators, and where access control sits in the whole process.Exam 4 · Templates, deduction and constraints25 questions on two-phase lookup and dependent names, the various sources of IFNDR, template argument deduction and SFINAE, partial ordering and specialization, CTAD, constraint satisfaction and subsumption, NTTPs, fold expressions, and discarded statements of if constexpr.Exam 5 · Expressions, evaluation order and constant evaluation25 questions on evaluation order, integral promotions and arithmetic conversions, shifts and out-of-range conversions, pointer comparison, the conditional operator, lambda captures and closure types, structured bindings, constant evaluation, immediate functions and static initialization order, with the emphasis on telling UB, unspecified behavior and implementation-defined behavior apart.Exam 6 · New rules from C++20 to C++2625 questions on the edges of rules added since C++20 - explicit object parameters, a few C++23 syntax relaxations, coroutine restrictions and parameter lifetimes, defaulted comparison and rewritten candidates, consteval and if consteval, exposures in modules, and C++26 erroneous behavior, the _ placeholder, pack indexing, structured binding packs and conditions, delete with a reason, static_assert messages, constexpr placement new, contracts and static reflection.

Practice