In C++ you decide where each object lives and when it dies, and the compiler trusts you: each file is compiled separately and the pieces are linked, and a broken rule is undefined behaviour, not an error. Python decides both things for you, which is why C++ is fast where you take care and silently wrong where you do not.
Fig. 1 follows one small program from its source files to the machine, in the order the pieces meet it. Each step names the section of this page, or the child page, that owns that piece, and links the child's own figure instead of drawing it again. Every number is from a recorded run on this page.
main.cpp (7 lines) calls count_tokens, tokens.h (4 lines) declares it, tokens.cpp (14 lines) defines it. Nothing runs yet: C++ has no run-time import, so a separate build turns them into a program (section 1).#include copies a whole file in, so main.cpp plus tokens.h plus the standard headers becomes one translation unit of 55,693 lines; tokens.cpp's is 55,700. Heights in the figure are on a log scale. Modules, the cure, are section 4.main.o (928 bytes) needs count_tokens (U), tokens.o (848 bytes) defines it (T). The compiler accepted main.cpp on the header's promise; section 1's stepper shows each stage.app (33,696 bytes). libc++ and libSystem stay outside it, loaded when the program starts: dynamic libraries (section 3).std::vector<float> v{1, 2, 3}: v itself is 24 bytes on the stack (pointer, size, capacity) and its three floats are 12 bytes on the heap, measured with a replaced operator new. Owner: Ownership, moves and lifetimes, whose stack and heap figure replays a real run with a copy and a move.~vector() runs at the brace: the heap bytes are freed, then v vanishes with its frame. One owner, one moment, no garbage collector: that is RAII (the ownership page, section 3). The vector itself is a class template from the standard library; how it grows its buffer is the vector figure on Classes, templates and the standard library.a and b own one 16-byte array and both free it. At -O0 the program crashed (exit code 133); at -O2 it printed "same array: 1" and exited normally; ASan reported "attempting double-free". No error from the compiler: section 2 and its gallery.You need: everyday Python. Nothing about C++ beyond having seen its syntax; each child page names what it assumes from this one.
.cpp file after the preprocessor has pasted in its headers; the compiler sees only this.o) and the names it defines or needsC++ is the language underneath most of the ML stack you use from Python: PyTorch's core, llama.cpp, ONNX Runtime, the CUDA kernels. The whole language follows from one decision: C++ gives you the machine's own representation of data and makes you responsible for how long each piece of it lives. Python decides both for you; Fig. 2 shows the difference on one vector. Six ideas follow from that:
| In Python | In C++ | Why C++ does it this way | Taught on |
|---|---|---|---|
| You run the source file | A compiler turns each .cpp file into machine code, then a linker joins the pieces into one program | Machine code runs without an interpreter, so loops cost nanoseconds, not tens of nanoseconds | Section 1 |
b = a makes a second name for the same object | auto b = a; makes a copy; you ask for a reference (&) or a pointer (*) explicitly | Values sit inline in memory, with no per-object header or reference count | Ownership, section 1 |
| Every object lives on the heap until the last reference goes | Local variables live on the stack and die at the closing brace; you choose the heap when you need it | The stack is free to allocate and free | Ownership, section 2 |
with open(...) for cleanup | RAII: every object's destructor runs at a known moment, so every resource is released by one | Deterministic cleanup with no garbage collector | Ownership, sections 3 and 4 |
| Assignment never copies a big object | Move semantics: a value can hand its heap buffer to another instead of being copied | Copy by default would otherwise make returning a vector expensive | Ownership, sections 5 to 7 |
| Bugs raise exceptions | Many bugs are undefined behaviour: no error, the program means nothing, and the optimiser may make it do anything | Checking every index and every overflow would cost speed; C++ checks only when you ask | Section 2 |
The rest is the toolkit you write with (classes, templates, the standard library, lambdas, errors: the classes page), what the CPU does with it (the machine page), and one real codebase read end to end (the llama.cpp page).
{ std::vector<float> v{1, 2, 3}; ... }v = [1.0, 2.0, 3.0]The same three numbers cost 12 bytes in C++ and 88 + 3 × 24 = 160 bytes in Python, and only C++ lets you point at the line where they are freed. Every rule on these pages follows from owning that moment: who frees, when, and what if two owners free the same bytes (the double free, section 2).
int main() { trace = true; std::printf("{ enter the block\n"); { std::vector<float> v{1.0f, 2.0f, 3.0f}; std::printf(" v itself: %zu bytes on the stack at %p (pointer, size, capacity)\n", sizeof v, (void*)&v); std::printf(" v.data(): %zu floats of %zu bytes on the heap at %p\n", v.size(), sizeof(float), (void*)v.data()); std::printf("} leave the block: v's destructor runs now\n"); } std::printf("after the block: nothing is left to free\n"); }
$ clang++ -std=c++23 -O2 -Wall -Wextra vector.cpp -o vector && ./vector
{ enter the block
operator new: 12 bytes on the heap at 0x105151410
v itself: 24 bytes on the stack at 0x16b1d6638 (pointer, size, capacity)
v.data(): 3 floats of 4 bytes on the heap at 0x105151410
} leave the block: v's destructor runs now
operator delete: heap 0x105151410 freed
after the block: nothing is left to free$ python3.14 vector.py
v is a name bound to a list object: 88 bytes on the heap
the list holds 3 pointers; each points at its own float object of 24 bytes
references to the list: 1 (the name v); it is freed when that count reaches 0
after del v: the count reached 0 and CPython freed the list (no destructor call you can see)
The C++ program replaces the global operator new and operator delete to print every heap allocation, so the line where the buffer is freed is visible. The addresses change from run to run; the stack address is far from the heap's.
Every output, compiler error, sanitizer report and number on these pages comes from a real run on an Apple M1 Pro (2026-10-05, reruns 2026-10-26; LLVM clang 23 for the sanitizers, Apple clang 17 otherwise; llama.cpp pinned at commit 8e16421).
| Finding | Where it is shown |
|---|---|
The optimiser changes what buggy code does: a double free crashed at -O0 and vanished at -O2; a data race lost updates at -O0 and gave the right answer at -O2 by luck. Sanitizers catch both. | The UB gallery, here |
An exception is free until thrown: throwing and catching one cost about 4.8 µs; returning a std::expected about 1 ns. | Classes, templates and the standard library, section 6 |
| Summing a matrix by columns was 52 to 56 times slower than by rows: same arithmetic, different cache behaviour. | The machine underneath, section 2 |
| Two threads writing counters on the same cache line ran 21 to 22 times slower; padding to 64 bytes still left about 2x, because this M1's lines are 128 bytes. | The machine underneath, section 8 |
On Apple Silicon with the default build, the ggml_vec_dot_* kernels most guides tell you to read run zero times: weights are repacked at load and 4x4 gemv/gemm kernels do every product. | Reading llama.cpp, section 10 |
| For a model this small, Metal generated tokens more slowly than 4 CPU threads: launching many tiny GPU kernels per token costs more than the work. | Reading llama.cpp, section 13 |
Python reads your source and runs it; import tokens finds tokens.py at run time. C++ has no run-time import. Building is a separate step with three stages, and most confusing C++ errors come from not knowing which stage complained.
# are text commands. #include "tokens.h" pastes the whole file in, literally. The result is one long file per .cpp, called a translation unit..o): machine code plus a table of the names (symbols) it defines and the ones it needs from elsewhere.The root page's token counter, split the way real projects are: a header (.h) declares the function (its name and types: a promise), a source file defines it (the body).
// tokens.h: the declaration (a promise that a definition exists somewhere) #pragma once #include <string_view> int count_tokens(std::string_view text);
// main.cpp: uses count_tokens; only sees the declaration #include "tokens.h" #include <cstdio> int main() { std::printf("%d tokens\n", count_tokens("C++ is fun, x86_64 too")); }
// tokens.cpp: the definition #include "tokens.h" #include <cctype> int count_tokens(std::string_view text) { int n = 0; bool inside = false; for (unsigned char c : text) { bool tok = std::isalnum(c) && c < 128; if (tok && !inside) n += 1; inside = tok; } return n; }
$ wc -l main.cpp tokens.h; clang++ -std=c++20 -E main.cpp | wc -l
for h in cstdio string_view vector string algorithm iostream; do printf "#include <%s> alone: " $h; printf "#include <$h>\\n" | clang++ -std=c++20 -x c++ -E - | wc -l | tr -d " "; done
7 main.cpp
4 tokens.h
11 total
55693
#include <cstdio> alone: 732
#include <string_view> alone: 55683
#include <vector> alone: 72835
#include <string> alone: 59542
#include <algorithm> alone: 54846
#include <iostream> alone: 93507Fifty-five thousand lines, nearly all from <string_view>.
Every .cpp that includes a standard header recompiles that header from text, which is why C++ builds are slow and why C++20 added modules (section 4) to replace textual inclusion.
The same three files through the three stages, with the real line counts, sizes, symbol tables and messages (Apple clang 17, -std=c++20); bars are to scale by line count. Predict before you pick "Forgot tokens.o": which stage fails, the compiler or the linker?
count_tokens, a .cpp that defines it, and main.cpp that calls it: 25 lines together.tokens.h, and through it the standard headers, into main.cpp: 55,693 lines for the compiler to read. The last lines are your code (the closed block under the pipeline shows them).tokens.cpp becomes its own translation unit of 55,700 lines. The two are processed separately; neither sees the other.main.o needs count_tokens and printf (U); tokens.o defines count_tokens (T). The compiler trusted the declaration in tokens.h.main.o's U count_tokens to tokens.o's T (now green), leaves printf to the dynamic system library, and writes the executable.main.o needs count_tokens (U), tokens.o defines it (T).count_tokens, so the linker (ld), not the compiler, fails: "Undefined symbols". The compile step had succeeded.util.h defines a function body, not just a declaration, and both a.cpp and b.cpp include it.twice().twice(int): two T entries for one name.inline (util_inline.h). The linker keeps one copy; the program links and exits with 0.tokens.cpp into a static library, libtokens.a, and links it into tokcount. Ninja records what each output was built from.tokens.cpp recompiles; the library and the program relink. main.cpp is untouched..cpp files include it, so both recompile: headers are why big C++ projects rebuild slowly.Reading a symbol table (nm): T (green) is defined here, U (red) is used here and defined elsewhere. The linker must find exactly one T for each U: none is "Undefined symbols", two is "duplicate symbol". The compiler accepted main.cpp on the header's promise alone, so a missing definition is always the linker's error.
The one definition rule (ODR) says a function may be defined once in the whole program. A function body in a header included from two .cpp files gives each object file its own copy: "duplicate symbol" from ld on macOS (GNU ld says "multiple definition"). The fix is inline ("identical copies may appear; keep one") or only a declaration in the header. Functions defined inside a class body, templates and constexpr functions are implicitly inline, which is why headers full of them link fine.
.pyi stub (types only) that every user pastes into their file. Python resolves names when the line runs; C++ resolves them at link time, so a missing or duplicated function is a build error, never a run-time NameError.CMake is the de facto standard build description: you list targets (executables, libraries) and their properties, and CMake generates the commands for a build tool such as Ninja. A real project separates a library from the program that uses it:
cmake_minimum_required(VERSION 3.28)
project(tokcount LANGUAGES CXX)
# A library target: compiled once, linked into anything that needs it
add_library(tokens src/tokens.cpp)
target_include_directories(tokens PUBLIC src) # users of tokens see src/
target_compile_features(tokens PUBLIC cxx_std_20) # and get C++20
target_compile_options(tokens PRIVATE -Wall -Wextra)
add_executable(tokcount src/main.cpp)
target_link_libraries(tokcount PRIVATE tokens) # brings the include dir and C++20 alongPUBLIC properties travel to every target that links the library; PRIVATE ones do not: the single most useful idea in CMake. In the generated commands, -Icmake2/src and -std=gnu++20 reached main.cpp; -Wall -Wextra did not. The library became a static library libtokens.a (an archive of object files, made by ar). The payoff of separate compilation is incremental builds: editing a .cpp recompiles one file, editing a header recompiles everything that includes it.
Names like count_tokens(std::__1::basic_string_view<...>) are C++'s mangled names decoded by nm -C: the parameter types are part of the symbol, which is how overloading works at link time. printf stays U after linking: it lives in libSystem, linked dynamically.
$ clang++ -std=c++20 -O2 -Wall -c tokens.cpp && clang++ -std=c++20 -O2 -Wall -c main.cpp && ls *.o
main.o
tokens.o
$ nm -C main.o; echo ---; nm -C tokens.o
U count_tokens(std::__1::basic_string_view<char, std::__1::char_traits<char> >)
0000000000000000 T _main
U _printf
000000000000003c s l_.str
0000000000000047 s l_.str.1
0000000000000000 t ltmp0
000000000000003c s ltmp1
0000000000000060 s ltmp2
---
U __DefaultRuneLocale
0000000000000000 T count_tokens(std::__1::basic_string_view<char, std::__1::char_traits<char> >)
U ___maskrune
0000000000000000 t ltmp0
00000000000000a8 s ltmp1
$ clang++ main.o -o app
Undefined symbols for architecture arm64:
"count_tokens(std::__1::basic_string_view<char, std::__1::char_traits<char>>)", referenced from:
_main in main.o
ld: symbol(s) not found for architecture arm64
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
[exit code 1]
$ clang++ main.o tokens.o -o app && ./app
6 tokens
#pragma once // A function DEFINED in a header, not marked inline int twice(int x) { return 2 * x; }
#include "util.h" int a(); int main() { return a() + twice(2) - 6; }
$ clang++ -std=c++20 -c a.cpp b.cpp && clang++ a.o b.o -o app
duplicate symbol 'twice(int)' in:
odr/a.o
odr/b.o
ld: 1 duplicate symbols
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
[exit code 1]
#pragma once // The fix: inline allows one identical definition per translation unit inline int twice(int x) { return 2 * x; }
$ sed -i.bak "s/util.h/util_inline.h/" a.cpp b.cpp && clang++ -std=c++20 -c a.cpp b.cpp && clang++ a.o b.o -o app && ./app; echo "exit code $?"
exit code 0
cmake_minimum_required(VERSION 3.28) project(hello LANGUAGES CXX) add_executable(hello main.cpp)
$ cmake -S . -B build -G Ninja -DCMAKE_CXX_COMPILER=clang++ > /dev/null && cmake --build build && ./build/hello
[1/2] Building CXX object CMakeFiles/hello.dir/main.cpp.o
[2/2] Linking CXX executable hello
hello from CMake
$ cmake -S . -B build -G Ninja && cmake --build build --verbose
clang++ -Icmake2/src -std=gnu++20 -arch arm64 -o CMakeFiles/tokcount.dir/src/main.cpp.o -c cmake2/src/main.cpp
clang++ -Icmake2/src -std=gnu++20 -arch arm64 -Wall -Wextra -o CMakeFiles/tokens.dir/src/tokens.cpp.o -c cmake2/src/tokens.cpp
cmake -E rm -f libtokens.a && ar qc libtokens.a CMakeFiles/tokens.dir/src/tokens.cpp.o && ranlib libtokens.a && cmake -E touch libtokens.a
clang++ -arch arm64 -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/tokcount.dir/src/main.cpp.o -o tokcount libtokens.a
$ ./build/tokcount
6 tokens
$ touch src/tokens.cpp && cmake --build build
[1/3] Building CXX object CMakeFiles/tokens.dir/src/tokens.cpp.o
[2/3] Linking CXX static library libtokens.a
[3/3] Linking CXX executable tokcount
$ touch src/tokens.h && cmake --build build
[1/4] Building CXX object CMakeFiles/tokcount.dir/src/main.cpp.o
[2/4] Building CXX object CMakeFiles/tokens.dir/src/tokens.cpp.o
[3/4] Linking CXX static library libtokens.a
[4/4] Linking CXX executable tokcount
$ cmake --build build
ninja: no work to do.
What it buys: each file compiles once, in parallel, and only what changed rebuilds. What it costs: headers are re-parsed in every file that includes them, and you maintain declarations and definitions separately. Common mistakes: a definition in a header without inline; global flags instead of per-target properties; forgetting -std= (section 4). llama.cpp's CMake build: the llama.cpp page, section 2.
The C++ standard lists operations whose result it does not define: reading outside an array or freed memory, overflowing a signed integer, reading an uninitialised variable, two threads writing one variable without synchronisation, falling off the end of a function that returns a value, and others. Such a program has undefined behaviour (UB): not "a wrong answer" but no meaning at all. The compiler is allowed to assume UB never happens, and its optimiser uses that assumption to delete checks and simplify code. So a program with UB can work at -O0 and break at -O2, or work today and break after a compiler upgrade. This is the deepest difference from Python, where every one of these is either impossible or an exception.
The classic example: "will x + 1 overflow?" written the obvious way.
#include <climits> #include <cstdio> // "Will adding 1 overflow?" written the way you would in Python __attribute__((noinline)) bool will_overflow(int x) { return x + 1 < x; // signed overflow is UB, so the compiler may assume x + 1 > x } int main() { std::printf("will_overflow(INT_MAX) = %d\n", will_overflow(INT_MAX)); }
-O2, what does will_overflow(INT_MAX) return? And at -O0?$ clang++-23 -std=c++23 -O0 overflow.cpp -o overflow && ./overflow
will_overflow(INT_MAX) = 1$ clang++-23 -std=c++23 -O2 overflow.cpp -o overflow && ./overflow
will_overflow(INT_MAX) = 0At -O0 the addition wrapped around to a negative number and the test said 1. At -O2 the compiler reasoned "signed overflow cannot happen, so x + 1 < x is always false" and compiled the function to return false.
Neither build reported anything. The same assumption is what makes signed loop counters fast: a signed counter never overflows, so i + 1 > i and the loop's trip count can be computed without wrap-around checks, which enables vectorisation and widening it to 64 bits. Sanitizers are compiler modes that add run-time checks for UB; UndefinedBehaviorSanitizer (UBSan) catches this one:
$ clang++-23 -std=c++23 -O2 -fsanitize=undefined overflow.cpp -o overflow && ./overflow
overflow.cpp:6:14: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior overflow.cpp:6:14
will_overflow(INT_MAX) = 1
(Under UBSan the program prints 1 again: the instrumented build computes the addition so it can check it.) The fix is to test before adding: x == INT_MAX, or __builtin_add_overflow, or C++26's <stdckdint.h> checked arithmetic. Unsigned integers do not have this problem: they wrap around by definition.
Each program was compiled with LLVM clang 23.1.2 without optimisation (-O0) and with it (-O2), and run; then with the tool that catches it: a sanitizer, a warning, or a hardened standard library. Every output is the real one. For each case, predict before you read the two runs: does the bug show at -O0, at -O2, or at neither? Notice how often a buggy program prints something plausible.
Commands as recorded by src/ca/steps/40_ub.sh; each run had a 5-second time limit. The uninitialised case printed "not seen" at -O0 and "seen" at -O2 for the same call, and the compiler warned only with -Wall.
-Wall -Wextra always, -Werror in CI. They caught the uninitialised read, the dangling string_view and the missing return in the gallery.v[i], front(), string_view bounds and more, turning silent UB into a trap..at(i) or a hardened library over raw indexing in non-hot code, smart pointers over new, values over references when lifetimes are unclear.-fsanitize=address (ASan), -fsanitize=undefined (UBSan), -fsanitize=thread (TSan). Slowdown: about 2 times for ASan per its documentation, 5 to 15 times for TSan per its documentation.-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST is meant for production (cheap checks, a silent trap); the _DEBUG mode prints why (the "Index past the end" case shows both).-ftrivial-auto-var-init=zero made the uninitialised example print "not seen" at -O2.Python has pip install and wheels. C++ has no official package manager, and the reason is technical: a compiled C++ library works with your program only if it was built with a compatible compiler, standard library and flags (the same ABI, application binary interface; the machine page, section 11). A mismatch gives link errors or, worse, silent memory corruption. So shipping prebuilt binaries is much harder than in Python, and the historical answer was "build it yourself" or "copy the source in". Three ways a library reaches your program:
inline functions and templates), so there is nothing to build or link: nlohmann/json, Catch2, Eigen. It sidesteps packaging and ABI, and costs compile time in every file that includes it..a, .lib): object files copied into your executable at link time, like libtokens.a in section 1. One self-contained binary; every program carries its own copy..dylib, .so, .dll): loaded when the program starts. Smaller binaries and shared updates, but the library must be present, at a compatible version, on the machine that runs it. Even the small program from section 1 depends on two, libc++ and libSystem:$ otool -L app
app:
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 2000.63.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1356.0.0)
Getting dependencies, oldest to newest: system packages, vendoring the source (llama.cpp does), CMake FetchContent, then the package managers vcpkg and Conan. The build system (CMake) and the package manager are separate tools, and there is no lock-file culture like uv.lock: pin versions and record the toolchain. Two files compiled with different flags that see different definitions of the same thing break the one definition rule, silently.
| Approach | How | Good for | Cost |
|---|---|---|---|
| System packages | brew install, apt install libfoo-dev, found with find_package or pkg-config | Quick local work | Whatever version the system ships; not reproducible |
| Vendoring, git submodules | Copy the source into your repo | Total control; very common: llama.cpp's vendor/ folder holds nlohmann/json, cpp-httplib, stb and miniaudio at the pinned commit | Manual updates |
CMake FetchContent | Name a git URL and tag in CMakeLists.txt; built with your project | A handful of dependencies | No lock file, no binary cache |
| vcpkg (Microsoft) | vcpkg.json manifest; builds from source with binary caching; a CMake toolchain file | New CMake projects | Another tool to learn |
| Conan (JFrog) | Binary packages described by profiles (compiler, standard library, architecture, build type) | Enterprises, CI-heavy setups | Heavier |
The root page is Topic: programming-languages (its Toolchain atlas tab). For Python bindings of C++ code, its Benchmark tab covers pybind11 and nanobind.
libtokens.a, section 1)otool -L app, below)Header-only trades build time for no packaging; static trades binary size for no run-time dependencies; dynamic shares one copy but needs a compatible version on every machine that runs it.
C++ is standardised by an ISO committee (WG21) on a three-year train: C++11, 14, 17, 20, 23, 26. Nothing old is removed, so "modern C++" is a subset you choose to write, the one these pages teach. Each compiler and standard library implements each standard gradually, and the two can differ: a feature needs both. The default language version differs between compilers and even versions of one compiler; measured here, Apple clang 17 defaults to C++14 and Apple clang 14 to C++98. So pass -std=c++20 or newer, or in CMake target_compile_features(t PUBLIC cxx_std_20). Write C++20 as the baseline and use C++23 where your compilers report it; C++26 is finished on paper and mostly not shipped.
$ for c in /usr/bin/clang++ clang++ clang++-23; do printf "%-18s default __cplusplus = " $c; echo __cplusplus | $c -x c++ -E -P - | tail -n 1; done
/usr/bin/clang++ default __cplusplus = 199711L
clang++ default __cplusplus = 201402L
clang++-23 default __cplusplus = 201703L
(199711L is C++98, 201402L C++14, 201703L C++17.) Elsewhere: GCC 16 (released 2026-04-30) is the first major compiler to default to C++20 (GCC 16 changes); upstream Clang has defaulted to C++17 since Clang 16 (Clang status); MSVC still defaults to C++14 (/std).
The standard way to ask a toolchain what it supports is the feature-test macros in <version>. This program prints them; "-" means not defined:
$ clang++ -std=c++26 features.cpp -o features17 && ./features17
__cplusplus 202400L
__cpp_concepts 202002
__cpp_lib_ranges 202406L
__cpp_lib_span 202002L
__cpp_lib_format 202110L
__cpp_impl_coroutine 201902L
__cpp_lib_jthread 201911L
__cpp_lib_expected 202211L
__cpp_lib_print 202207L
__cpp_lib_mdspan 202406L
__cpp_lib_ranges_to_container 202202L
__cpp_lib_generator -
__cpp_lib_flat_map 202207L
__cpp_lib_stacktrace -
__cpp_explicit_this_parameter -
__cpp_lib_modules 202207L
__cpp_contracts -
__cpp_impl_reflection -
__cpp_lib_simd -
__cpp_lib_senders -
__cpp_pack_indexing 202311L$ clang++-23 -std=c++26 features.cpp -o features23 && ./features23
__cplusplus 202400L
__cpp_concepts 202002
__cpp_lib_ranges 202406L
__cpp_lib_span 202002L
__cpp_lib_format 202110L
__cpp_impl_coroutine 201902L
__cpp_lib_jthread 201911L
__cpp_lib_expected 202211L
__cpp_lib_print 202207L
__cpp_lib_mdspan 202406L
__cpp_lib_ranges_to_container 202202L
__cpp_lib_generator -
__cpp_lib_flat_map 202511L
__cpp_lib_stacktrace -
__cpp_explicit_this_parameter 202110L
__cpp_lib_modules 202207L
__cpp_contracts -
__cpp_impl_reflection -
__cpp_lib_simd -
__cpp_lib_senders -
__cpp_pack_indexing 202311L| Standard | What matters for you | Status here (Apple clang 17 / LLVM clang 23) |
|---|---|---|
| C++20 (the baseline to write) | Concepts, ranges, std::span, std::format, <=>, coroutines (language machinery only), std::jthread, modules | All reported by both, modules aside (see below) |
| C++23 (usable now) | std::expected, std::print, ranges::to, std::mdspan (a multidimensional view over a flat buffer: the standard way to pass a tensor), std::flat_map, deducing this, import std;, std::generator, std::stacktrace | Most reported by both; std::generator and std::stacktrace by neither; deducing this only by clang 23 |
| C++26 (technical work finished 2026-03-28) | Static reflection (P2996: code that inspects types at compile time, e.g. enum-to-string and bindings without macros), contracts (P2900: pre, post, contract_assert), std::execution (P2300: a standard model for asynchronous and parallel work), a hardened standard library (P3471), erroneous behaviour for uninitialised reads (P2795), std::simd, std::inplace_vector, std::hive, <linalg> | Reflection, contracts, std::execution and std::simd reported by neither; Clang's status page lists reflection, contracts and P2795 as "No". GCC 16 implements reflection (behind -freflection), contracts and P2795 |
Sources: Sutter's trip report, "C++26 is done" (reflection, contracts, std::execution, hardening, erroneous behaviour); cppreference's C++26 page (paper numbers, the other library additions); GCC 16 changes and Clang's C++ status (compiler support). For any feature, cppreference's compiler support tables are the place to check.
Modules replace textual #include with compiled interfaces (import std;), attacking the 55,000-line problem of section 1. The language feature is in C++20 and import std in C++23, but tooling still lags: GCC 16's notes say modules support "is still experimental and must be enabled by -fmodules", and CMake supports named modules since 3.28 but import std only behind an experimental gate (cmake-cxxmodules). Headers remain the pragmatic default in 2026; llama.cpp uses them.
/std:c++23 with Build Tools 14.52": not yet true. The current release is 14.51 in Visual Studio 2026 18.10.3 (2026-09-29) and Microsoft's documentation still lists /std:c++23preview (root page, Toolchain atlas corrections).Each of these compiles. Most are lifetime bugs: a second owner, or a reference that outlives its owner.
| Mistake | What actually happens | Shown on |
|---|---|---|
A string_view, span or range view that outlives its owner | Views do not own; one made from a temporary dangles at the semicolon | Gallery |
A reference, pointer or iterator into a vector, kept across push_back | Growth reallocates and frees the old buffer. Use indices, or reserve first | Gallery; Classes, section 4 |
| A lambda that captures a local by reference and outlives it | It reads a dead stack slot, often plausibly | Gallery; Classes, section 5 |
| A destructor that frees, with the compiler-written copy left in place | Two objects own one buffer and both free it: a double free | Gallery; Ownership, section 7 |
Using an object after std::move | Valid but unspecified. Assign to it or let it die | Ownership, section 5 |
shared_ptr by reflex | Cycles leak; atomic counting slows every copy; ownership becomes unclear. unique_ptr first | Ownership, section 4 (measured) |
| Slicing a derived object into a base by value; a public non-virtual destructor in a base used through pointers | The derived part is dropped, or never destroyed. Pass polymorphic objects by reference or pointer | Classes, section 2 |
| Static initialisation order across files | Globals in different .cpp files are initialised in an unspecified order | Below |
| Unsigned arithmetic going below zero | 0 - 1 wraps to 18,446,744,073,709,551,615 | Below |
| Treating a data race as "sometimes a wrong value" | It is UB: the race printed 1098717 instead of 2000000 at -O0 and the right answer at -O2, so a test at -O2 passes | Gallery; Machine, section 8 |
for (auto& x : make().items()), dangled until C++23 extended the lifetime of every temporary in the range-for initializer (P2718); the same expression outside a range-for still dangles, so the old page's "fixed for some cases in C++23, not all" stands.static, which is initialised on first use.for (size_t i = v.size() - 1; i >= 0; --i): size_t is unsigned, so i >= 0 is always true; an empty vector makes even the first value huge. Mixing signed and unsigned in a comparison converts the signed side to unsigned (clang warns with -Wextra).std::atomic or a mutex.new/delete; unique_ptr by default.std::vector, std::string, unique_ptr) and write no special member at all; if you must write one, write all five, with noexcept moves.string_view and span<const T> to read; never store them past the call without thought.const by default; constexpr where a value can be computed at compile time.auto for iterators, lambdas and long type names; concrete types at API boundaries.-std=c++20 or newer and -Wall -Wextra (-Werror in CI); ASan, UBSan and TSan in CI test runs; clang-format and clang-tidy; CMake targets with PUBLIC/PRIVATE properties, presets, and vcpkg or Conan.Each stands alone and assumes only this page; the order below is the one the ideas build in. Times are each child's own header (230 words a minute), with the closed blocks counted apart; each card names the child's 3D figures, which Fig. 1 links step by step.
Every object has exactly one lifetime, and RAII plus moves let ownership, not a garbage collector, decide when it ends. Replayed from real constructor and destructor logs. Figures: the stack and heap of one run, a copy and a move; owners and reference counts.
Abstractions are resolved at compile time unless you ask for run-time dispatch, and the costs are measured: virtual calls, templates, the standard library, lambdas, exceptions against std::expected. Figures: a virtual call followed through memory; a vector's size against its capacity.
Memory, not arithmetic, sets the speed; caches, layout and SIMD decide it. Caches, layout, assembly, SIMD, branches, atomics and the ABI, all measured on an M1 Pro. Figures: the cache ladder, AoS against SoA, SIMD schedules, message passing, false sharing.
One token is a ggml graph built, planned and run by threads over repacked quantised blocks, traced through the code and timed end to end. Figures: one decoded token, layer 0 of the real graph, one quantised block, the KV cache.
Elsewhere: the same program in Python, C++, Rust and TypeScript, and the benchmark across them, is Topic: programming-languages. The sibling language pages are Python: the essentials, Rust: the essentials and JavaScript and TypeScript: the essentials. Kernels and CUDA C++ are in Topic: cuda-and-gpu-programming; the KV cache, batching and serving in Topic: inference-and-serving.
Every output was produced by src/ca/run_all.sh on an Apple M1 Pro under macOS 27: the build and the gallery on 2026-10-05 (Apple clang 17.0.0 with the macOS 26 SDK; LLVM clang 23.1.2 for the gallery and sanitizers; CMake 4.4.4 with Ninja), the hero on 2026-10-26 (Apple clang 17, CPython 3.14.8). This page replaces the old written pages "C++: zero to expert" and "C++: modern practice and standards status"; every claim from them was checked, with corrections in boxes on the page that owns each subject. Rebuilt on 2026-10-26 as the essentials page of four children.
Links checked 2026-10-05. Times for outside sources are rough reading or viewing times; each child page has its own Further reading for its subject.
auto, though it stops at C++14. Book, about 8 h.