C++ — Reference
Source: https://en.cppreference.com/w/cpp
C++
- Created: 1979 (as “C with Classes”) by Bjarne Stroustrup at Bell Labs; renamed C++ in 1983
- Latest stable: C++23 (ISO/IEC 14882:2024, published 2024); C++26 in progress
- Paradigms: multi-paradigm — procedural, object-oriented, generic, functional, metaprogramming
- Typing: static, nominal, with type inference (
auto), concepts (C++20) - Memory: manual (RAII + smart pointers); no GC
- Compilation: AOT compiled to native, separate compilation + link
- Primary domains: systems, embedded, games (engines), HFT/trading, browsers, OS kernels, scientific computing, GPU/CUDA hosts
- Official docs: https://en.cppreference.com/w/cpp ; https://isocpp.org/
1. At a glance
- Standardized by ISO/IEC JTC1/SC22/WG21. Three-year cadence: C++17, C++20, C++23, C++26 (planned 2026).
- Major implementations: GCC (libstdc++), Clang/LLVM (libc++), MSVC (Microsoft STL), Apple Clang, Intel oneAPI DPC++.
- Backwards-compatible with C at the source/ABI boundary (mostly); routinely used to host other languages’ runtimes.
- Tooling rebooted around LSP via clangd and modules in C++20+.
2. Getting started
-
Install: Linux:
apt install g++ordnf install gcc-c++. macOS:xcode-select --install(Apple Clang). Windows: Visual Studio Build Tools or MSYS2/MinGW-w64. Cross-platform: download from https://gcc.gnu.org/ or https://releases.llvm.org/. -
Version managers: none official. Use distro packages, Homebrew (
brew install llvm), or Conan/vcpkg toolchain files.nix-shell/ Docker for reproducibility. -
Hello, world (C++23):
import std; // C++23 standard-library module int main() { std::println("Hello, world!"); }Compile:
g++ -std=c++23 hello.cpp -o helloorclang++ -std=c++23 -fmodules hello.cpp. -
Project layout: no enforced layout. Common:
src/,include/<project>/,tests/,CMakeLists.txt. CMake’s “modern target-based” style is dominant. -
Build tools: CMake is de facto; Meson, Bazel, xmake, Make, Ninja also common. Package managers: vcpkg (Microsoft) and Conan (JFrog).
-
REPL/playground: Cling / xeus-cling (Jupyter); Compiler Explorer (godbolt.org) is the universal scratchpad.
3. Basics
- Primitives:
bool,char/wchar_t/char8_t/char16_t/char32_t, fixed-widthint8_t…int64_t,float/double/long double, C++23std::float16_t/bfloat16_t. Literals:0x,0b,0, raw stringsR"(...)", user-defined literals42_km. - Variables:
auto x = 1;(deduced),const,constexpr,consteval,constinit. Block scope; RAII destruction in reverse construction order. - Control flow:
if/else,if constexpr(compile-time),if consteval(C++23),switch(with[[fallthrough]]),for, range-forfor (auto& x : v),while,do-while, structured bindingsauto [k, v] = pair;. - Functions: default args, overloading, templates,
autoreturn, trailing return typeauto f() -> int. Lambdas[capture](args) -> ret { ... }; generic lambdas[](auto x){...}; static lambdas (C++23). First-class viastd::function/ function pointers. - Strings:
std::string(owning),std::string_view(non-owning, C++17),std::format(C++20),std::print/println(C++23). No native interpolation; usestd::format("{} {}", a, b). - Collections:
std::array,std::vector,std::deque,std::list,std::map/std::unordered_map,std::set/std::unordered_set,std::tuple,std::pair,std::span(C++20),std::mdspan(C++23),std::flat_map/flat_set(C++23).
4. Intermediate
- Generics: templates over types, non-type values, and template templates. C++20 concepts constrain templates:
template<std::integral T>. CTAD (Class Template Argument Deduction). Variadic templates + parameter packs. - Modules: C++20
export module foo;/import foo;.import std;(C++23) replaces<iostream>etc. Build-system support is still maturing — CMake 3.28+ with Ninja 1.11+. - Namespaces:
namespace foo { ... }, nestednamespace foo::bar, anonymous namespaces for TU-local symbols,usingdeclarations and directives. - Error handling: exceptions (
throw/try/catch);std::expected<T,E>(C++23) for value-or-error;std::optional<T>; assertions via<cassert>.noexceptparticipates in overload resolution and codegen. - Concurrency:
std::thread,std::jthread(C++20, joins on dtor + cancellation token),std::mutex/std::shared_mutex,std::atomic<T>,std::condition_variable,std::future/std::async. Coroutines (C++20):co_await/co_yield/co_return.std::generator(C++23). Parallel STL:std::execution::par/par_unseq. - I/O & networking:
<iostream>,<fstream>,std::filesystem(C++17),<print>(C++23). No standard networking yet (std::netdeferred to C++26+); use Asio/Boost.Asio. - Stdlib highlights:
<ranges>(C++20) views & pipelines,<chrono>(calendars, time zones, parsing in C++20),<format>,<source_location>,<bit>,<numbers>,<random>,<regex>.
5. Advanced
- Memory model: explicit. Use
std::unique_ptr/std::shared_ptr/std::weak_ptrovernew/delete. Custom allocators viaAllocatorconcept;std::pmr::polymorphic_allocatorfor arena-style. Alignment viaalignas/alignof. Memory order (memory_order_*) on atomics; the C++ memory model (since C++11) defines happens-before with sequenced-before, synchronizes-with, modification order. - Concurrency deep dive: atomics with explicit memory order, lock-free queues,
std::stop_tokencooperative cancellation, executors (TS/proposed),std::latch/std::barrier(C++20). C++26 addsstd::execution(sender/receiver) andstd::hazard_pointer/std::rcu. - FFI:
extern "C"for C linkage. Direct interop with C; complex with other languages via C wrappers, SWIG, pybind11 (Python), cppyy, CXX (Rust), JNI (Java), N-API (Node). - Reflection: none in C++23 beyond
typeid/std::source_location/ type traits. Static reflection (^^,[: :]) is targeted for C++26 (P2996). - Performance tooling:
perf, VTune, AMD uProf, valgrind/cachegrind, callgrind, heaptrack, gperftools, sanitizers (-fsanitize=address,undefined,thread,memory),[[nodiscard]],[[likely]]/[[unlikely]],__builtin_expect, PGO (-fprofile-generate/-fprofile-use), LTO (-flto), ThinLTO.
6. God mode
- Templates as a Turing-complete metalanguage: SFINAE →
enable_if→ C++20 concepts +requiresclauses. CRTP (template<class D> struct Base { auto& self() { return static_cast<D&>(*this); } }). constexpr/consteval/constinit: entire algorithms run at compile time;constevalrequires immediate evaluation. C++20 allowsstd::vectorandstd::stringin constexpr.- Coroutines machinery: customize via
promise_type(return type,initial_suspend/final_suspend,await_transform); awaitables implementawait_ready/await_suspend/await_resume. Stackless, heap-allocated by default — HALO (Heap Allocation eLision Optimization) often elides it. - Modules + header units:
import <vector>;produces a BMI (binary module interface). Build systems must scan forimport/moduledeclarations (P1689) — CMake/Ninja support is mandatory. - Reflection (C++26):
^^Tproduces a reflection value;[: e :]splices it back into source. Will replace much TMP. - Placement new + EBO (Empty Base Optimization) +
[[no_unique_address]](C++20) for zero-overhead composition. std::launder: required to bless pointers after object lifetime tricks (e.g., reusing storage). Gets right answer where compilers would assume aliasing-free.- Custom allocators:
Allocatorconcept,std::pmrfor runtime polymorphism, NUMA-aware allocation, slab/arena allocators. - Link-time tricks:
--gc-sections,--icf=safe(identical-code-folding), section-based code layout, BOLT/Propeller for post-link optimization. - UB catalog awareness: signed overflow, OOB access, use-after-free, strict aliasing violations, unsequenced modifications, data races. Use UBSan/ASan religiously.
- Embedding: C++ embeds well into anything that takes a C ABI; the runtime dependencies are minimal (
libstdc++/libc++,libgcc/compiler-rt, libc).
7. Idioms & style
- Naming: no single convention — Google uses
snake_casefor vars,CamelCasefor types; LLVM usesCamelCasefor types andcamelBackfor methods. Pick one andclang-formatit. - Formatter: clang-format (Google/LLVM/Microsoft/Mozilla styles built in). Linter: clang-tidy (modernize-, bugprone-, performance-*).
- Idiomatic patterns: RAII for everything (lock guards, file handles, allocations); rule of zero/three/five; pass by value-and-move;
const-correctness; preferenum class; preferstd::array/std::spanover C arrays;std::unique_ptrovernew;autofor verbose type names; AAA (Almost Always Auto); CRTP / type erasure /std::variantovervoid*. - Reviewers look for: ownership semantics, lifetime issues,
noexceptcorrectness, value-category mistakes (move fromconst, dangling rvalue refs), thread-safety annotations, allocator awareness in hot paths, lack of[[nodiscard]].
8. Ecosystem
- GUI: Qt, wxWidgets, Dear ImGui, JUCE, GTKmm, Slint.
- Game engines: Unreal Engine, CRYENGINE, Godot (core), Lumberyard/O3DE.
- HPC/scientific: Eigen, Armadillo, Boost, Kokkos, OpenMP, MPI, CUDA, SYCL.
- Web/network: Drogon, Crow, cpp-httplib, Boost.Beast, Boost.Asio, gRPC.
- Testing: GoogleTest, Catch2, doctest, Boost.Test.
- Doc tools: Doxygen, Sphinx + Breathe + Exhale, Standardese, mkdocs + Doxygen.
- Where it’s used: browsers (Chromium, Firefox), databases (PostgreSQL extensions, MongoDB, MySQL, ClickHouse), Adobe/Autodesk creative apps, financial trading systems, embedded firmware, Microsoft Office, Photoshop, all major game engines, LLVM itself.
9. Gotchas
- Undefined behavior is everywhere: signed-integer overflow, OOB array access, dereferencing null/invalid pointers, use-after-free, uninitialized reads, strict-aliasing violations, double-frees, unsynchronized data races. UBSan + ASan + TSan are not optional in serious code.
- Most vexing parse:
Widget w();declares a function, not a default-constructedWidget. - Initializer-list constructor preference:
std::vector<int> v{3, 0};is{3, 0}(size 2), not “3 zeros.” Usestd::vector<int> v(3, 0). - Object slicing: copying a derived into a base by value drops the derived parts.
- Returning references to locals / dangling iterators after container reallocation.
std::vector<bool>is not a container ofbool(proxy refs).- Implicit narrowing conversions in non-brace-init contexts.
- ABI fragility:
std::stringSBO sizes differ across libstdc++ vs libc++; mixing across libraries causes corruption. - Headers vs modules ordering: macros leak in headers; module imports do not.
- Move-from objects are still destructible but in unspecified state; don’t reuse without reassigning.
- Template error messages without concepts can be 200 lines; use concepts and
static_assert.
10. Citations
- cppreference (C++ language + library): https://en.cppreference.com/w/cpp
- isocpp.org Standard Status (C++23 published, C++26 WIP): https://isocpp.org/std/status
- C++23 / ISO/IEC 14882:2024 overview, deducing this, std::expected, std::print, std::flat_map, mdspan, std::generator: https://en.wikipedia.org/wiki/C%2B%2B23
- Compiler Explorer (godbolt): https://godbolt.org/
- CMake docs: https://cmake.org/documentation/
- clang-format / clang-tidy: https://clang.llvm.org/docs/ClangFormat.html ; https://clang.llvm.org/extra/clang-tidy/
- LLVM coding standard: https://llvm.org/docs/CodingStandards.html
- Google C++ Style Guide: https://google.github.io/styleguide/cppguide.html
- C++ Core Guidelines (Stroustrup/Sutter): https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines