Skip to content

Search topics & cppreference

Search all study topics, concept maps, and 6,587 C++ and C reference pages.

C++ across revisions

Thirty-six language and library shifts from C++11 through C++26. Each milestone pins the ISO paper, standard clause, abstract-machine change, and self-contained code ready for Compiler Explorer.

Showing 36 of 36 milestones
C++11LanguageN3055[basic.lval]

Value category taxonomy & rvalue references

Split expressions along identity and movability into glvalue, prvalue, and xvalue so rvalue references (T&&) can steal resources safely from expiring objects.

cpp11-value-categories.cpp
#include <utility>

struct Buffer {
    int* ptr = nullptr;
    Buffer() = default;
    Buffer(Buffer&& other) noexcept : ptr(other.ptr) {
        other.ptr = nullptr;
    }
};

Buffer make_buffer();

void consume(Buffer b) {
    (void)b;
}

void transfer_resource() {
    Buffer named;
    consume(std::move(named)); // std::move casts lvalue -> xvalue so Buffer&& runs
}
C++11LanguageN2235[dcl.constexpr]

Generalized constant expressions (constexpr)

Moved pure computations from template metaprogramming hacks into typed compile-time functions and variables guaranteed usable inside constant expressions.

cpp11-constexpr.cpp
constexpr int factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}

constexpr int fact5 = factorial(5);
static_assert(fact5 == 120, "Evaluated at compile time");
C++11LanguageN2927[expr.prim.lambda]

Lambda expressions & closure types

Replaced handwritten functor structs with inline lexical closures whose unnamed compiler-generated class holds captured state as data members.

cpp11-lambdas.cpp
#include <algorithm>
#include <vector>

int count_above(const std::vector<int>& xs, int threshold) {
    return static_cast<int>(std::count_if(
        xs.begin(), xs.end(),
        [threshold](int v) { return v > threshold; }
    ));
}
C++11LibraryN2429[intro.multithread]

Multi-threaded memory model & std::atomic

Defined threads, data races as undefined behavior, and happens-before synchronization edges via std::atomic and explicit memory orders.

cpp11-memory-model.cpp
#include <atomic>

struct Channel {
    int payload = 0;
    std::atomic<bool> ready{false};

    void publish(int v) {
        payload = v;
        ready.store(true, std::memory_order_release);
    }

    bool try_consume(int& out) {
        if (!ready.load(std::memory_order_acquire)) return false;
        out = payload; // Sequenced after acquire-load sees release-store
        return true;
    }
};
C++11LibraryN1856[unique.ptr]

Exclusive ownership with std::unique_ptr

Replaced broken copy-transfers-ownership semantics of std::auto_ptr with move-only RAII ownership enforceable at zero size overhead.

cpp11-unique-ptr.cpp
#include <memory>
#include <utility>

struct Handle { int fd; };

std::unique_ptr<Handle> acquire_handle(int fd) {
    return std::unique_ptr<Handle>(new Handle{fd});
}

void transfer_owner() {
    auto owner = acquire_handle(3);
    auto next_owner = std::move(owner); // owner becomes nullptr
    (void)next_owner;
}
C++11LibraryN2951[forward]

std::move & std::forward perfect forwarding

Combined template argument deduction on T&& with reference-collapsing rules so std::forward preserves lvalue or rvalue category across wrappers.

cpp11-perfect-forwarding.cpp
#include <utility>

void sink(int&) {}
void sink(int&&) {}

template <class T>
void relay(T&& arg) {
    sink(std::forward<T>(arg));
}

void demo_relay() {
    int x = 10;
    relay(x);  // T deduces as int&, forwards lvalue
    relay(20); // T deduces as int, forwards rvalue
}
C++14LanguageN3638[dcl.type.auto.deduct]

Function auto & decltype(auto) return deduction

Enabled compilers to deduce return types from return statements while decltype(auto) preserves exact reference and cv-qualifiers in forwarding wrappers.

cpp14-return-deduction.cpp
#include <utility>

template <class Container>
decltype(auto) first_element(Container&& c) {
    return std::forward<Container>(c)[0]; // Preserves reference if operator[] returns T&
}

int read_first() {
    int arr[2] = {7, 9};
    first_element(arr) = 42;
    return arr[0];
}
C++14LanguageN3649[expr.prim.lambda.closure]

Generic lambdas with auto parameters

Turned a closure's operator() into a member function template when parameters use auto, letting one lambda accept arbitrary types without a named template.

cpp14-generic-lambdas.cpp
int sum_pairs() {
    auto add = [](const auto& a, const auto& b) {
        return a + b;
    };
    return add(3, 4) + static_cast<int>(add(1.5, 2.5));
}
C++14LanguageN3652[dcl.constexpr]

Relaxed constexpr functions with locals & loops

Lifted C++11's single-return restriction so constexpr functions can declare mutable local variables, run loops, and branch like ordinary imperative code.

cpp14-relaxed-constexpr.cpp
constexpr int sum_up_to(int limit) {
    int acc = 0;
    for (int i = 1; i <= limit; ++i) {
        acc += i;
    }
    return acc;
}

static_assert(sum_up_to(10) == 55, "Imperative constexpr loop");
C++14LibraryN3656[unique.ptr.create]

Exception-safe std::make_unique

Closed the exception-safety gap in calls like f(unique_ptr(new A), unique_ptr(new B)) by wrapping allocation and ownership inside one atomic factory call.

cpp14-make-unique.cpp
#include <memory>

struct Node {
    int id;
    Node(int i) : id(i) {}
};

std::unique_ptr<Node> build_node(int id) {
    return std::make_unique<Node>(id);
}
C++14LibraryN3657[associative.reqmts]

Heterogeneous associative lookup (is_transparent)

Allowed ordered containers with transparent comparators such as std::less<> to search by compatible key views without allocating temporary std::string keys.

cpp14-transparent-lookup.cpp
#include <functional>
#include <map>
#include <string>

bool has_key(const std::map<std::string, int, std::less<>>& m, const char* key) {
    return m.find(key) != m.end(); // No temporary std::string constructed
}
C++14LibraryN3659[thread.sharedtimedmutex]

Shared reader-writer locks (std::shared_timed_mutex)

Added multiple-reader / single-writer synchronization primitives so concurrent readers share access via std::shared_lock while writers acquire exclusive locks.

cpp14-shared-locking.cpp
#include <mutex>
#include <shared_mutex>

struct ConfigCache {
    mutable std::shared_timed_mutex mtx;
    int revision = 0;

    int read() const {
        std::shared_lock<std::shared_timed_mutex> lock(mtx);
        return revision;
    }

    void bump() {
        std::unique_lock<std::shared_timed_mutex> lock(mtx);
        ++revision;
    }
};
C++17LanguageP0135R1[class.copy.elision]

Guaranteed copy elision & prvalue materialization

Redefined prvalues as unmaterialized initialization instructions rather than temporary objects, mandating zero-copy construction directly into destination storage.

cpp17-guaranteed-elision.cpp
struct Immovable {
    int value;
    explicit Immovable(int v) : value(v) {}
    Immovable(const Immovable&) = delete;
    Immovable(Immovable&&) = delete;
};

Immovable make_immovable() {
    return Immovable(99); // Guaranteed direct initialization, no move needed
}
C++17LanguageP0217R3[dcl.struct.bind]

Structured bindings decomposition

Introduced declarative binding of subobjects or tuple-like elements to named identifiers bound directly to a hidden decomposed object.

cpp17-structured-bindings.cpp
#include <map>
#include <string>

bool insert_once(std::map<std::string, int>& counts, const std::string& k) {
    auto [it, inserted] = counts.emplace(k, 1);
    if (!inserted) ++(it->second);
    return inserted;
}
C++17LanguageP0145R3[intro.execution]

Strict expression evaluation order

Sequenced postfix expressions, shift chains, and assignments left-to-right (or right-to-left for =) so chained calls and index updates no longer have unspecified order.

cpp17-eval-order.cpp
#include <map>

int update_entry(std::map<int, int>& table, int key) {
    // RHS of '=' is guaranteed sequenced before table[key] lookup
    return table[key] = static_cast<int>(table.size());
}
C++17LibraryP0137R1[ptr.launder]

std::launder & placement-new object identity

Separated pointer provenance from raw storage reuse so replacement objects with const or reference members remain reachable without stale devirtualization.

cpp17-launder.cpp
#include <new>

struct ConstBox {
    const int id;
};

int reuse_const_box() {
    alignas(ConstBox) unsigned char storage[sizeof(ConstBox)];
    ConstBox* first = new (storage) ConstBox{1};
    first->~ConstBox();
    new (storage) ConstBox{2};
    return std::launder(first)->id; // Must launder to observe id == 2
}
C++17LibraryP0088R3[variant]

Type-safe discriminated union (std::variant)

Provided a stack-allocated sum type tracking its active alternative safely in the type system instead of error-prone tagged C unions.

cpp17-variant.cpp
#include <string>
#include <variant>

using Result = std::variant<int, std::string>;

int extract_or_zero(const Result& r) {
    return std::visit([](const auto& val) -> int {
        if constexpr (std::is_same_v<decltype(val), const int&>) {
            return val;
        }
        return 0;
    }, r);
}
C++17LibraryP0220R1[string.view]

Non-owning std::string_view & std::optional

Standardized borrowed pointer-plus-length string slices and nullable value wrappers so APIs avoid heap allocations when inspecting read-only text or absent values.

cpp17-string-view.cpp
#include <optional>
#include <string_view>

std::optional<std::string_view> trim_prefix(std::string_view sv, std::string_view pfx) {
    if (sv.size() < pfx.size() || sv.substr(0, pfx.size()) != pfx) {
        return std::nullopt;
    }
    sv.remove_prefix(pfx.size());
    return sv;
}
C++20LanguageP0734R0[temp.constr.order]

Concepts, requires-clauses & subsumption

Replaced brittle SFINAE traits with named boolean constraints participating directly in overload partial ordering via atomic-constraint subsumption.

cpp20-concepts.cpp
#include <concepts>

template <typename T>
concept SignedInt = std::integral<T> && std::signed_integral<T>;

template <std::integral T>
constexpr int classify(T) { return 1; }

template <SignedInt T>
constexpr int classify(T) { return 2; } // Subsumes std::integral

static_assert(classify(-7) == 2);
C++20LanguageP0912R5[dcl.fct.def.coroutine]

Stackless coroutines (co_await, co_yield, co_return)

Added compiler-synthesized heap/elided coroutine frames controlled by promise_type hooks, enabling suspension without OS thread stacks.

cpp20-coroutines.cpp
#include <coroutine>

struct Task {
    struct promise_type {
        Task get_return_object() { return {}; }
        std::suspend_never initial_suspend() noexcept { return {}; }
        std::suspend_never final_suspend() noexcept { return {}; }
        void return_void() noexcept {}
        void unhandled_exception() {}
    };
};

Task ping() {
    co_await std::suspend_never{};
    co_return;
}
C++20LanguageP0515R3[expr.spaceship]

Three-way comparison (operator<=>)

Collapsed six relational boilerplates into defaulted operator<=> plus compiler-synthesized rewritten candidates for <, <=, >, >=, and !=.

cpp20-spaceship.cpp
#include <compare>

struct SemVer {
    int major;
    int minor;
    auto operator<=>(const SemVer&) const = default;
};

static_assert(SemVer{2, 0} > SemVer{1, 9});
static_assert(SemVer{2, 0} == SemVer{2, 0});
C++20LibraryP0896R4[ranges.syn]

Composable std::ranges views & niebloids

Replaced unchecked iterator pairs with constrained ranges, lazy view pipelines via operator|, and ADL-proof niebloid function objects.

cpp20-ranges.cpp
#include <ranges>
#include <vector>

int sum_even_squares(const std::vector<int>& nums) {
    int total = 0;
    for (int v : nums
               | std::views::filter([](int x) { return x % 2 == 0; })
               | std::views::transform([](int x) { return x * x; })) {
        total += v;
    }
    return total;
}
C++20LibraryP0122R7[views.span]

Contiguous non-owning std::span

Unified raw arrays, std::array, and std::vector parameters into one bounds-aware pointer+size view with optional compile-time static extent.

cpp20-span.cpp
#include <span>

int sum_bytes(std::span<const int> items) {
    int acc = 0;
    for (int v : items.subspan(0, items.size())) {
        acc += v;
    }
    return acc;
}
C++20LibraryP0660R10[thread.jthread]

RAII std::jthread & cooperative stop_token

Fixed std::thread's destructor std::terminate trap by automatically requesting cancellation and joining on scope exit.

cpp20-jthread.cpp
#include <stop_token>
#include <thread>

void run_worker() {
    std::jthread worker([](std::stop_token st) {
        while (!st.stop_requested()) {
            break;
        }
    });
} // Automatically calls request_stop() and join()
C++23LanguageP0847R7[dcl.fct]

Explicit object parameters (deducing this)

Let member functions declare an explicit 'this Self&&' first parameter, unifying const/ref overloads and replacing CRTP boilerplate.

cpp23-deducing-this.cpp
#include <utility>

struct Cell {
    int data = 0;

    template <class Self>
    auto&& get(this Self&& self) {
        return std::forward<Self>(self).data;
    }
};

int read_cell() {
    const Cell c{42};
    return c.get(); // Self deduced as const Cell&
}
C++23LanguageP2266R3[class.copy.elision]

Simpler implicit move for move-eligible returns

Unified implicit-move rules so any move-eligible local or parameter in return, co_return, or throw behaves directly as an xvalue during overload resolution.

cpp23-implicit-move.cpp
struct Sink {};
struct Source {
    operator Sink() const& = delete;
    operator Sink() && { return {}; }
};

Sink convert(Source s) {
    return s; // Move-eligible parameter picks operator Sink() && in C++23
}
C++23LanguageP2718R0[stmt.ranged]

Range-based for temporary lifetime extension

Extended all temporaries created inside a range-based for initializer expression until the loop finishes, curing chained accessor dangling bugs.

cpp23-range-for-lifetime.cpp
#include <vector>

struct Holder {
    std::vector<int> items{1, 2, 3};
    const std::vector<int>& get() const { return items; }
};

int sum_holder() {
    int total = 0;
    for (int x : Holder{}.get()) { // Holder temporary lives across whole loop in C++23
        total += x;
    }
    return total;
}
C++23LibraryP0323R12[expected]

std::expected<T, E> monadic error handling

Standardized a sum type holding either an expected value T or error E with monadic combinators (and_then, transform, or_else) for exception-free pipelines.

cpp23-expected.cpp
#include <expected>

enum class ParseErr { empty };

std::expected<int, ParseErr> parse_port(bool ok) {
    if (!ok) return std::unexpected(ParseErr::empty);
    return 8080;
}

int resolve_port(bool ok) {
    return parse_port(ok)
        .transform([](int p) { return p + 1; })
        .value_or(80);
}
C++23LibraryP2093R14[print.fun]

Compile-time checked std::print & std::println

Combined compile-time checked format strings with direct Unicode-aware terminal output, eliminating iostream state flags and printf type mismatches.

cpp23-print.cpp
#include <print>

void log_metric(int count, double ms) {
    std::println("Processed {} items in {:.2f} ms", count, ms);
}
C++23LibraryP2590R2[obj.lifetime]

std::start_lifetime_as implicit object creation

Gave low-level deserialization and DMA buffers a defined abstract-machine primitive to begin implicit-lifetime object existence in-place without UB.

cpp23-start-lifetime-as.cpp
#include <memory>

struct PacketHeader {
    unsigned int magic;
    unsigned int length;
};

unsigned int read_magic(const void* wire_bytes) {
    const auto* hdr = std::start_lifetime_as<PacketHeader>(wire_bytes);
    return hdr->magic;
}
C++26LanguageP2900R14[basic.contract]

Contract assertions (pre, post, contract_assert)

Moved preconditions, postconditions, and inline assertions into checked language syntax with constified predicates and selectable evaluation semantics.

cpp26-contracts.cpp
#include <contracts>

int clamp_nonneg(const int value, const int limit)
    pre(limit >= 0)
    post(r: r >= 0 && r <= limit)
{
    contract_assert(limit >= 0);
    if (value < 0) return 0;
    return value > limit ? limit : value;
}
C++26LanguageP2996R13[expr.reflect]

Value-based static reflection (^^ and [:refl:])

Replaced macro serialization and recursive template traits with first-class consteval std::meta::info values queried via ^^ and spliced back with [:refl:].

cpp26-static-reflection.cpp
#include <cstddef>
#include <meta>

struct Metric {
    int count;
    double latency;
};

consteval std::size_t member_count() {
    return std::meta::nonstatic_data_members_of(
        ^^Metric, std::meta::access_context::current()
    ).size();
}

static_assert(member_count() == 2);
C++26LanguageP2795R5[basic.indet]

Erroneous behavior & [[indeterminate]]

Replaced uninitialized-local undefined behavior with bounded erroneous behavior unless a buffer explicitly opts back in via [[indeterminate]].

cpp26-erroneous-behavior.cpp
#include <cstddef>

int bounded_erroneous_read() {
    int uninit; // Erroneous value in C++26: deterministic runtime, no UB time travel
    return uninit;
}

std::byte raw_scratch() {
    [[indeterminate]] std::byte page[1024]; // Explicit opt-out for uninitialized scratch
    page[0] = std::byte{0x42};
    return page[0];
}
C++26LibraryP2300R10[exec]

std::execution senders, receivers & schedulers

Standardized composable lazy async task graphs connecting schedulers, senders, and receivers across three completion channels without eager allocations.

cpp26-execution.cpp
// C++26 P2300R10 standard library syntax (<execution>)
#include <execution>
#include <thread>
#include <utility>

int run_async_graph(std::execution::scheduler auto sched) {
    namespace ex = std::execution;
    auto work = ex::schedule(sched)
        | ex::then([] { return 21; })
        | ex::then([](int v) { return v * 2; });
    auto [res] = std::this_thread::sync_wait(std::move(work)).value();
    return res;
}
C++26LibraryP0843R14[inplace.vector]

std::inplace_vector<T, N> fixed-capacity storage

Delivered a resizable contiguous sequence container backed entirely by inline storage inside the object, eliminating heap allocations and pointer chasing.

cpp26-inplace-vector.cpp
#include <inplace_vector>

int build_inline_batch() {
    std::inplace_vector<int, 4> batch;
    batch.push_back(10);
    batch.push_back(20);
    return batch.front() + batch.back();
}
C++26LibraryP0792R14[func.wrap.ref]

Non-owning std::function_ref callable view

Added a lightweight two-pointer type-erased view over any callable, eliminating std::function heap allocations and template code bloat for callbacks.

cpp26-function-ref.cpp
#include <functional>

int apply_twice(std::function_ref<int(int)> fn, int x) {
    return fn(fn(x));
}

int test_callback() {
    return apply_twice([](int v) { return v + 3; }, 10);
}