C++ Reference
Every C++ keyword, operator, container, algorithm, standard library class and modern language feature in one place. Concise, accurate pages with live examples that compile and run on GCC 15 in C++23 mode, with syntax, parameters and return values.
Keywords and Statements
-
if and elseConditionals, if constexpr, init statements. -
switchSwitch statements and [[fallthrough]]. -
forClassic for loops. -
Range-based forIterating ranges, structured bindings. -
while and do-whileCondition-controlled loops. -
break and continueLeaving and skipping iterations. -
gotoJumps and why to avoid them. -
returnReturning values and RVO. -
try, catch and throwException handling. -
noexceptException specifications. -
class and structDefining classes. -
unionUnions and std::variant alternative. -
enum and enum classEnumerations. -
namespaceNamespaces. -
usingAliases and using-declarations. -
typedefType aliases (legacy). -
templateTemplates. -
typenameDependent names and type parameters. -
concept and requiresConcepts (C++20). -
constConst correctness. -
constexprCompile-time evaluation. -
consteval and constinitImmediate functions, constant init. -
staticStatic storage and members. -
externLinkage. -
mutableMutable members. -
volatileVolatile access. -
inlineInline functions and variables. -
virtualVirtual functions. -
override and finalOverriding rules. -
explicitExplicit constructors. -
friendFriend declarations. -
operatorOperator overloading. -
new and deleteDynamic allocation. -
thisThe current object. -
autoType deduction. -
decltypeType of an expression. -
sizeof and alignofSize and alignment. -
static_assertCompile-time assertions. -
static_cast, dynamic_cast, const_cast, reinterpret_castCasts. -
typeidRuntime type information. -
nullptrThe null pointer literal. -
= default and = deleteDefaulted and deleted functions. -
co_await, co_yield, co_returnCoroutines. -
import and moduleModules (C++20). -
Attributes[[nodiscard]], [[maybe_unused]], [[likely]]. -
alignasAlignment control. -
thread_localThread storage. -
asmInline assembly. -
Reserved wordsKeywords and alternative tokens.
Types and Language Concepts
-
Fundamental typesint, char, bool, floating types. -
Fixed-width integer types<cstdint>. -
LiteralsInteger, floating, string, user-defined literals. -
Raw string literalsR"(...)". -
ReferencesLvalue references. -
Rvalue references and move semanticsstd::move, moved-from state. -
Forwarding referencesT&& and std::forward. -
PointersRaw pointers and pitfalls. -
ArraysC-style arrays and decay. -
Structured bindingsauto [a, b]. -
InitializationDirect, copy, list, value initialization. -
Brace initializationNarrowing and initializer_list. -
Designated initializersC++20. -
Copy elision and RVOGuaranteed elision. -
Rule of three, five and zeroSpecial members. -
ConstructorsDelegating, converting, default. -
Destructors and RAIIResource management. -
InheritanceBase and derived classes. -
PolymorphismVirtual dispatch. -
Abstract classesPure virtual functions. -
Multiple and virtual inheritanceDiamond problem. -
Object slicingPitfall. -
Access specifierspublic, protected, private. -
Static membersClass-level state. -
Operator overloadingRules and idioms. -
Three-way comparisonoperator<=> (C++20). -
Implicit and explicit conversionsUser-defined conversions. -
Lambda expressionsCaptures and generic lambdas. -
Function objectsFunctors. -
Function templatesDeduction and overloading. -
Class templatesSpecialization. -
Variadic templatesParameter packs and fold expressions. -
Template specializationFull and partial. -
SFINAESubstitution failure. -
ConceptsConstraining templates. -
Class template argument deductionCTAD. -
Compile-time programmingconstexpr and consteval. -
Undefined behaviorCommon causes. -
One Definition RuleODR. -
Name lookup and ADLArgument-dependent lookup. -
Overload resolutionHow calls are resolved. -
Value categorieslvalue, prvalue, xvalue. -
Object lifetimeStorage duration and lifetime. -
The memory modelThreads and ordering. -
ModulesImport and export. -
CoroutinesCoroutine machinery. -
Ranges and viewsRange concepts. -
Exception safetyGuarantees. -
The pimpl idiomHiding implementation. -
CRTPCuriously recurring template pattern. -
Type traitsMetaprogramming.
Operators
-
Arithmetic operators+, -, *, /, %. -
Increment and decrement++ and --. -
Assignment operators= and compound forms. -
Comparison operators==, <, <=>. -
Logical operators&&, ||, !. -
Bitwise operators&, |, ^, ~, <<, >>. -
Conditional operator?:. -
Member access operators., ->, .*, ->*. -
Scope resolution::. -
Subscript operatoroperator[]. -
Function call operatoroperator(). -
Stream operators<< and >> for I/O. -
Address-of and dereference& and *. -
Comma operatorSequencing. -
Operator precedenceThe table. -
sizeof operatorRules. -
new and delete operatorsAllocation functions. -
Alternative tokensand, or, not.
Containers
-
Containers overviewChoosing a container. -
std::vectorDynamic arrays. -
vector::push_back and emplace_backAdding elements. -
vector::insert and eraseInserting and erasing. -
vector::reserve and capacityCapacity. -
vector<bool>The special case. -
std::arrayFixed-size arrays. -
std::dequeDouble-ended queue. -
std::listDoubly linked list. -
std::forward_listSingly linked list. -
std::mapOrdered map. -
map::insert, emplace, find, operator[]Map access. -
std::unordered_mapHash map. -
std::setOrdered set. -
std::unordered_setHash set. -
std::multimap and multisetDuplicates allowed. -
std::flat_map and flat_setFlat associative containers (C++23). -
std::stackStack adapter. -
std::queueQueue adapter. -
std::priority_queueHeap adapter. -
std::spanNon-owning views. -
std::mdspanMultidimensional views (C++23). -
std::stringStrings. -
std::string_viewNon-owning string views. -
std::bitsetFixed bit sets. -
std::pairPairs. -
std::tupleTuples. -
std::optionalOptional values. -
std::variantType-safe unions. -
std::anyType-erased values. -
std::expectedValue or error (C++23). -
Iterator categoriesInput to contiguous. -
IteratorsUsing iterators. -
Iterator invalidationRules per container. -
Allocatorsstd::allocator and pmr. -
Polymorphic memory resourcesstd::pmr. -
Container complexityBig-O table. -
Erase-remove idiom and std::eraseRemoving elements. -
Sorting and orderingComparators. -
Heterogeneous lookupTransparent comparators. -
Node handlesextract and merge.
Strings and I/O
-
std::string constructorsCreating strings. -
string::append and operator+=Appending. -
string::find and rfindSearching. -
string::substrSubstrings. -
string::replace and eraseModifying. -
string::compareComparing. -
string::size, length, capacitySizes. -
stoi, stod and to_stringConversions. -
to_chars and from_charsFast conversions. -
string_view operationsViews. -
std::formatFormatting (C++20). -
std::print and printlnPrinting (C++23). -
Format specificationsThe mini-language. -
Custom formattersstd::formatter. -
iostream overviewcin, cout, cerr. -
std::coutStandard output. -
std::cinStandard input. -
std::getlineReading lines. -
<iomanip>setw, setprecision, setfill. -
std::stringstreamString streams. -
std::fstreamFile streams. -
ifstream and ofstreamReading and writing files. -
Stream statesgood, fail, eof. -
Stream buffersrdbuf. -
std::spanstreamSpan-based streams (C++23). -
std::filesystemPaths and directories. -
Filesystem operationscopy, remove, directory_iterator. -
std::regexRegular expressions. -
regex_search and regex_matchMatching. -
regex_replaceReplacing. -
Localesstd::locale. -
Unicode in C++char8_t, u8 strings. -
<cctype>Character classification.
Algorithms
-
Algorithms overviewCategories. -
std::sortSorting. -
std::stable_sort and partial_sortOther sorts. -
std::nth_elementSelection. -
std::find and find_ifSearching. -
std::count and count_ifCounting. -
all_of, any_of, none_ofPredicates. -
std::for_eachApplying functions. -
std::transformMapping. -
std::copy and copy_ifCopying. -
std::move (algorithm)Moving ranges. -
std::fill and generateFilling. -
std::iotaSequences. -
std::accumulateFolding. -
std::reduce and transform_reduceParallel-friendly folding. -
partial_sum and inclusive_scanPrefix sums. -
reverse and rotateRearranging. -
std::uniqueRemoving duplicates. -
std::remove and remove_ifRemoving elements. -
std::replace and replace_ifReplacing. -
std::partitionPartitioning. -
binary_search, lower_bound, upper_boundBinary search. -
std::equal_rangeRanges of equals. -
merge and inplace_mergeMerging. -
set_union, set_intersection, set_differenceSorted set algorithms. -
make_heap, push_heap, pop_heapHeap algorithms. -
min, max, minmax, clampExtremes. -
min_element and max_elementFinding extremes. -
equal and mismatchComparing ranges. -
lexicographical_compareOrdering ranges. -
next_permutationPermutations. -
shuffle and sampleRandomizing. -
search and adjacent_findSubsequence search. -
swap and iter_swapSwapping. -
Execution policiesParallel algorithms. -
Constrained algorithmsstd::ranges versions. -
ProjectionsRanges projections. -
Range viewsfilter, transform, take, drop. -
Composing viewsPipelines with |. -
C++23 range additionszip, enumerate, chunk, to. -
std::ranges::toMaterializing ranges. -
<numeric>gcd, lcm, midpoint. -
<bit>popcount, countl_zero, rotl. -
Algorithm complexityGuarantees. -
Writing comparatorsStrict weak ordering.
Memory and Utilities
-
std::unique_ptrExclusive ownership. -
std::shared_ptrShared ownership. -
std::weak_ptrNon-owning observers. -
make_unique and make_sharedFactories. -
enable_shared_from_thisSelf sharing. -
Custom deletersDeleters. -
RAIIResource idiom. -
Dynamic memorynew, delete, arrays. -
Placement newConstructing in place. -
Allocation failuresbad_alloc. -
Smart pointer pitfallsCycles and misuse. -
std::move and std::forwardMoving. -
std::swap and exchangeSwapping. -
std::functionType-erased callables. -
std::move_only_functionC++23. -
std::bind and bind_frontBinding. -
std::invokeUniform invocation. -
std::reference_wrapperReference semantics. -
std::hashHashing. -
<type_traits>Traits. -
std::enable_ifConditional templates. -
is_same, is_base_of, is_convertibleTrait queries. -
std::numeric_limitsType limits. -
std::chronoTime library. -
chrono::durationDurations. -
chrono clockssteady_clock and system_clock. -
chrono calendar and time zonesC++20 dates. -
<random>Random numbers. -
Random enginesmt19937 and friends. -
Random distributionsuniform, normal, etc. -
std::ratioCompile-time fractions. -
std::complexComplex numbers. -
std::valarrayNumeric arrays. -
<cmath>Math functions. -
<cstdlib>Utilities. -
std::source_locationSource info. -
std::stacktraceStack traces (C++23). -
std::exception hierarchyStandard exceptions. -
std::error_codeError codes. -
std::unreachable and assumeOptimization hints. -
std::byteswap and bit_castBit operations.
Concurrency
-
std::threadThreads. -
std::jthreadJoining threads (C++20). -
std::mutexMutual exclusion. -
lock_guard, unique_lock, scoped_lockLocks. -
std::shared_mutexReader-writer locks. -
std::condition_variableWaiting for conditions. -
std::atomicAtomics. -
Memory orderingmemory_order. -
std::future and promiseFutures. -
std::asyncAsync tasks. -
std::packaged_taskTask wrappers. -
call_once and once_flagOne-time init. -
std::latch and barrierSynchronization (C++20). -
std::counting_semaphoreSemaphores. -
std::stop_tokenCooperative cancellation. -
thread_local storagePer-thread data. -
DeadlockPrevention. -
Data racesDetection and avoidance. -
Parallel algorithmsPolicies in practice. -
hardware_concurrencyCore counts. -
std::this_threadsleep_for, yield. -
Coroutines in practiceGenerators and tasks. -
std::generatorC++23.
Preprocessor, Tools and Concepts
-
#includeIncluding headers. -
#defineMacros. -
#if, #ifdef, #ifndefConditional compilation. -
#pragmaPragmas. -
Predefined macros__cplusplus and friends. -
Feature-test macros__cpp_*. -
Include guardsGuarding headers. -
CompilersGCC, Clang, MSVC. -
Compiler flagsWarnings and optimization. -
Compiling and linkingODR and libraries. -
CMakeBuild systems (read-only). -
SanitizersASan, UBSan, TSan (read-only). -
Debugginggdb (read-only). -
Testing frameworksCatch2, GoogleTest (read-only). -
Static analysisclang-tidy (read-only). -
C++ standardsC++98 to C++26. -
What is new in C++20Feature tour. -
What is new in C++23Feature tour. -
What is coming in C++26Reflection, contracts (read-only). -
Core GuidelinesModern practice. -
Naming and formattingConventions. -
Common idiomsPatterns. -
Error handling strategiesExceptions vs. expected. -
Performance tipsPractical advice. -
GlossaryKey C++ terms.
Nothing matches โโ. Try the site search.