C++ 12 min read

C++23 Features: The Complete Guide & Reference Manual

Share this article
C++23 Features: The Complete Guide & Reference Manual

C++23 marks one of the most productive and pragmatic milestones in the language's modern evolution. By standardizing powerful primitives that developers previously had to pull from external libraries (like Boost or Abseil) or implement through complex boilerplate, C++23 drastically cuts down code bloat and enhances type safety.

Whether you are eliminating exceptions with std::expected, optimizing cache performance with flat associative containers, streamlining multi-dimensional spans with std::mdspan, or speeding up build times with modules (import std;), modern C++ changes how enterprise applications are built.

In this comprehensive guide, we break down every major C++23 core and standard library feature, comparing how they work today against the legacy workarounds we used before C++23.

Part 1: Core Language Features

1. Explicit Object Member Functions (deducing this)

  • What it does: Allows explicit parameterization of the object parameter (this) in member functions, eliminating duplicate const/non-const overloads and simplifying recursive lambdas.

Before C++23:

class Widget {
public:
    // Required writing duplicate code for const and non-const correctness
    void process() & {
        internalProcess();
    }
    void process() const & {
        internalProcess();
    }
private:
    void internalProcess() const;
};

After C++23:

class Widget {
public:
    template <typename Self>
    void process(this Self&& self) {
        // Automatically preserves value category and cv-qualification for 'self'
        self.internalProcess();
    }
};

2. Multidimensional Subscript Operator ([i, j])

  • What it does: Allows the subscript operator to take multiple arguments, streamlining custom multi-dimensional containers and matrices.

Before C++23:

class Matrix {
public:
    // Required overloading operator() or returning a proxy object for operator[]
    double& operator()(size_t row, size_t col);
};

Matrix mat;
mat(1, 2) = 5.0; // Function call syntax instead of true indexing

After C++23:

class Matrix {
public:
    // True multi-argument subscript operator
    double& operator[](size_t row, size_t col);
};

Matrix mat;
mat[1, 2] = 5.0; // Natural multidimensional syntax

3. if consteval / if not consteval

  • What it does: Explicitly branches code depending on whether evaluation is happening at compile-time (constexpr) or run-time.

Before C++23:

constexpr int compute(int x) {
    // std::is_constant_evaluated() requires boolean checks and lacks strict compile-time guarantees
    if (std::is_constant_evaluated()) {
        return fastCompileTimeHash(x);
    } else {
        return optimizedRuntimeHash(x);
    }
}

After C++23:

constexpr int compute(int x) {
    if consteval {
        return fastCompileTimeHash(x); // Guaranteed to compile only at compile-time
    } else {
        return optimizedRuntimeHash(x); // Guaranteed runtime execution path
    }
}

4. auto(x) and auto{x} (Decay Copy Expressions)

  • What it does: Creates a temporary, prvalue copy of an expression via decay, making it safe to capture or return references to temporary modifications.

Before C++23:

// Verbose explicit type construction to force a temporary copy
std::string process(const std::string& input) {
    auto temp = std::string(input);
    temp[0] = 'A';
    return temp;
}

After C++23:

std::string process(const std::string& input) {
    // auto(input) creates a decayed prvalue copy cleanly
    return auto(input) = [] (auto& s) { s[0] = 'A'; return s; } (auto(input));
}

5. Static and Deducing Lambdas

  • What it does: Allows lambdas to be marked static (preventing accidental capture of this) and makes parameter lists optional for stateless lambdas.

Before C++23:

// Stateless lambdas still generated closure types with hidden pointer overhead
auto ptr = [](int a, int b) { return a + b; };

// Cannot make stateless lambda explicitly static to ensure zero capture
class MyClass {
    void registerCallback() {
        // Accidentally captures 'this' implicitly if not careful
        doSomething([]{ return 42; });
    }
};

After C++23:

// 1. Optional parameter list for stateless lambdas with no args
auto getConst = [] { return 42; };

class MyClass {
    void registerCallback() {
        // Explicitly static lambda guarantees zero 'this' capture overhead
        doSomething([] static { return 42; });
    }
};

6. Attribute [[assume(expr)]]

  • What it does: Hints to the compiler that an expression evaluates to true, allowing the optimizer to generate faster assembly instructions.

Before C++23:

int divide(int a, int b) {
    // Non-portable compiler-specific intrinsics
#if defined(_MSC_VER)
    __assume(b != 0);
#elif defined(__clang__) || defined(__GNUC__)
    __builtin_assume(b != 0);
#endif
    return a / b;
}

After C++23:

int divide(int a, int b) {
    // Standardized portable attribute
    [[assume(b != 0)]];
    return a / b;
}

7. Extended constexpr Capabilities

  • What it does: Relaxes compile-time restrictions, allowing non-literal variables, local goto statements, and try-catch blocks inside constexpr functions.

Before C++23:

constexpr int complexCalc(int x) {
    // Error before C++23: try-catch blocks and local gotos were forbidden in constexpr
    try {
        if (x < 0) goto error_handler;
        return x * 2;
    } catch (...) {
        return 0;
    }
error_handler:
    return -1;
}

After C++23:

constexpr int complexCalc(int x) {
    // Fully supported in C++23 compile-time execution contexts
    try {
        if (x < 0) goto error_handler;
        return x * 2;
    } catch (...) {
        return 0;
    }
error_handler:
    return -1;
}

8. UTF-8 Source File Encoding & Named Universal Character Escapes

  • What it does: Mandates UTF-8 source file encoding natively and allows human-readable named character escapes.

Before C++23:

// Dependent on host machine code pages (Windows-1252 vs. UTF-8)
// and raw hex escapes for special symbols
const char* msg = "Hello \u1F431";

After C++23:

// Source files guaranteed to be interpreted as UTF-8 natively,
// with explicit named character escape sequences
const char* msg = "Hello \N{CAT FACE}";

Part 2: Standard Library Features

Here are the Before and After C++23 code examples for the remaining standard library features and modules:

1. std::expected<T, E> (Monadic Error Handling)

  • What it does: Holds either a desired value (T) or an unexpected error (E), making error-handling explicit without throwing exceptions.

Before C++23:

// Using Boost.Outcome or third-party tl::expected
tl::expected<int, std::error_code> parseConfig() {
    if (!isOpen()) return tl::unexpected(make_error_code(std::errc::io_error));
    return 42;
}

After C++23:

#include <expected>

std::expected<int, std::error_code> parseConfig() {
    if (!isOpen()) return std::unexpected(std::make_error_code(std::errc::io_error));
    return 42;
}

2. std::print and std::println

  • What it does: Type-safe, fast formatted output stream writing directly to standard outputs without <iostream> bloat.

Before C++23:

#include <iostream>
#include <fmt/core.h> // Using the external {fmt} library

// Either bloated iostreams or external formatting libraries
fmt::print("User: {}, ID: {}\n", username, id);

After C++23:

#include <print>

std::print("User: {}, ID: {}\n", username, id);

3. Expanded Ranges (std::views::zip, enumerate, adjacent, chunk)

  • What it does: Extends ranges to cleanly zip multiple containers, chunk sequences, or track indices automatically during iteration.

Before C++23:

#include <vector>

// Manual index tracking or Boost.Range utilities
for (size_t i = 0; i < keys.size(); ++i) {
    process(keys[i], values[i]);
}

After C++23:

#include <ranges>
#include <vector>

for (auto [key, val] : std::views::zip(keys, values)) {
    process(key, val);
}

4. std::ranges::to

  • What it does: Converts any C++20 range directly into a container (e.g., auto vec = subrange | std::views::to<std::vector>();).

Before C++23:

#include <vector>
#include <algorithm>
#include <ranges>

auto filtered = numbers | std::views::filter([](int n) { return n % 2 == 0; });
std::vector<int> vec;
std::copy(filtered.begin(), filtered.end(), std::back_inserter(vec));

After C++23:

#include <vector>
#include <ranges>

auto vec = numbers | std::views::filter([](int n) { return n % 2 == 0; })
                   | std::views::to<std::vector>();

5. Flat Associative Containers (std::flat_map, std::flat_set)

  • What it does: Cache-friendly associative containers backed by contiguous flat vectors rather than node-based red-black trees.

Before C++23:

#include <map> // Node-based overhead with poor cache locality
// Or using Boost.Container flat_map
boost::container::flat_map<int, std::string> map;

After C++23:

#include <flat_map>

// Backed by contiguous vectors for optimal cache performance
std::flat_map<int, std::string> map;
map[1] = "One";

6. std::mdspan (Multi-Dimensional Span)

  • What it does: A non-owning multidimensional array view that maps coordinates to a contiguous block of memory without data overhead.

Before C++23:

// Manual pointer arithmetic or external Eigen / Boost.MultiArray libraries
std::vector<double> raw_data(100);
double val = raw_data[y * width + x]; // Manual coordinate mapping

After C++23:

#include <mdspan>
#include <vector>

std::vector<double> raw_data(100);
std::mdspan matrix(raw_data.data(), 10, 10);
double val = matrix[y, x]; // Clean multidimensional mapping view

7. std::generator<T> (Coroutines Generator)

  • What it does: Standardizes synchronous coroutine-based generator sequences cleanly via standard library support.

Before C++23:

// Required writing complex custom promise_type structures and coroutine boilerplate
CustomGenerator<int> generateSequence() {
    co_yield 1;
    co_yield 2;
}

After C++23:

#include <generator>

std::generator<int> generateSequence() {
    co_yield 1;
    co_yield 2;
}

8. std::stacktrace

  • What it does: Captures and formats the current thread's stack trace programmatically.

Before C++23:

// Using Boost.Stacktrace or OS-specific code (execinfo.h / DbgHelp.h)
#include <boost/stacktrace.hpp>
auto trace = boost::stacktrace::stacktrace();

After C++23:

#include <stacktrace>
#include <print>

auto trace = std::stacktrace::current();
std::println("{}", trace);

9. std::move_only_function

  • What it does: A polymorphic function wrapper similar to std::function, but supporting move-only callable objects (non-copyable functors/lambdas).

Before C++23:

// std::function requires copyable objects, forcing shared_ptr workarounds for move-only objects
auto ptr = std::make_unique<Resource>();
std::function<void()> fn = [p = std::move(ptr)]() { /* use p */ }; // Error: not copyable!

After C++23:

#include <functional>
#include <memory>

auto ptr = std::make_unique<Resource>();
std::move_only_function<void()> fn = [p = std::move(ptr)]() { /* use p */ }; // Perfectly valid

10. Utility Additions: std::byteswap and std::to_underlying

  • What it does: std::byteswap reverses endianness; std::to_underlying cleanly casts an enum to its underlying integer type.

Before C++23:

enum class Status : uint8_t { Active = 1, Inactive = 0 };

Status s = Status::Active;
// Verbose casts and non-portable builtin macros
auto val = static_cast<std::underlying_type_t<Status>>(s);
uint32_t swapped = __builtin_bswap32(0x12345678);

After C++23:

#include <bit>
#include <utility>

enum class Status : uint8_t { Active = 1, Inactive = 0 };

Status s = Status::Active;
auto val = std::to_underlying(s); // Clean standard cast
uint32_t swapped = std::byteswap(0x12345678); // Standard endian swap

Part 3: Standard Library Modules

. import std; (Replacing Header Includes)

  • What it does: Standardizes experimental modules to replace slow header preprocessor includes with fast direct module imports.

Before C++23:

// Slow preprocessor header inclusion causing massive compilation translation unit overhead
#include <vector>
#include <string>
#include <iostream>

After C++23:

// Fast, pre-compiled module import
import std;

int main() {
    std::vector<std::string> v{"Hello", "Modules"};
}