Skip to content
Tutorials Center
My learning

Topics

Lesson 141 of 171 ยท Modern C++ and Beyond

Modern C++ Features by Standard

A tour of what each C++ standard added, from C++11 lambdas and smart pointers to C++23 std::print and std::expected, with runnable examples and a C++26 preview.

"Modern C++" usually means C++ as it has been written since C++11, the release that changed the language so much that its own creator described it as feeling like a new language. Since then a new standard has arrived every three years: C++14, C++17, C++20, C++23, and next, C++26. Each one made code shorter, safer and faster to write, and old habits that tutorials and Stack Overflow answers still show (raw new, NULL, output parameters, printf, macro tricks) now have better replacements.

This lesson is a guided tour, one standard at a time. For each, you'll see the headline features in tiny examples and a link to the lesson that covers them in depth. It's also a practical reference: when you read code and wonder "is this C++17 or C++20?", or when a compiler says "only available with -std=c++20", this page tells you where a feature came from. The final section previews C++26, clearly labeled, since compilers are still implementing it.

Which standard am I compiling?

Every compiler accepts a flag that picks the language version: -std=c++17, -std=c++20, -std=c++23 for GCC and Clang, /std:c++20 or /std:c++latest for MSVC. Our editor uses -std=c++23. Inside a program, the macro __cplusplus tells you the version, and feature-test macros tell you whether a particular feature is available, which is how portable libraries adapt to older compilers.

C++ Detecting the standard and features

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The values are dates: 201703L is C++17, 202002L is C++20, 202302L is C++23. Each feature macro holds the date of the proposal version that's implemented. On our server you'll see C++23 values. Note that __cplusplus was famously stuck at 199711L on MSVC unless you pass /Zc:__cplusplus; feature-test macros are the reliable way to check.

C++11: the big reset

C++11 (published 2011, after years known as "C++0x") is the foundation everything else stands on:

  • auto type deduction and range-based for loops (auto, for loops).
  • Lambdas: inline anonymous functions (Lambda Expressions).
  • Move semantics and rvalue references: cheap transfers of resources (Move Semantics).
  • Smart pointers: std::unique_ptr and std::shared_ptr (unique_ptr, shared_ptr and weak_ptr).
  • nullptr, enum class, brace initialization and std::initializer_list.
  • constexpr functions (limited to a single return statement in C++11), static_assert, override and final, = default and = delete.
  • Variadic templates, decltype, type aliases with using.
  • A memory model and threads: std::thread, std::mutex, std::atomic, std::future (Threads).
  • New library pieces: std::array, std::unordered_map, std::tuple, <chrono>, <random>, <regex>.

C++14 (2014) was a polishing release: generic lambdas (auto parameters), std::make_unique, return type deduction for normal functions, relaxed constexpr (loops and variables allowed), lambda init captures ([p = std::move(ptr)]), binary literals (0b1010) and digit separators (1'000'000).

C++ C++11 and C++14 in one program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++17: everyday conveniences

C++17 (2017) is the standard many companies still target as their minimum. Its features remove small annoyances everywhere:

  • Structured bindings: auto [key, value] = pair; (std::pair and std::tuple).
  • if and switch with initializers: if (auto it = m.find(k); it != m.end()) (if, else if and else).
  • if constexpr for compile-time branches in templates, and fold expressions for parameter packs (Variadic Templates).
  • Class template argument deduction (CTAD): std::pair p{1, 2.0}; with no <int, double>.
  • Vocabulary types: std::optional, std::variant, std::any and std::string_view (std::optional, std::variant ..., std::string_view).
  • std::filesystem, parallel algorithms (std::execution::par), std::from_chars/to_chars.
  • Inline variables, nested namespaces (namespace a::b {}), attributes [[nodiscard]], [[maybe_unused]] and [[fallthrough]].
  • Guaranteed copy elision: returning a temporary never copies or moves it.
C++ C++17 features at work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++20: the second revolution

C++20 (2020) is as large as C++11 and introduced the "big four", plus a long list of smaller gems:

  • Concepts: named constraints on templates, with readable errors (Concepts and Constraints).
  • Ranges: algorithms that take whole containers, and lazy, composable views with | (Ranges and Views).
  • Coroutines: co_yield, co_await, co_return (Coroutines).
  • Modules: export module and import, replacing headers (C++20 Modules).
  • The three-way comparison <=> and defaulted comparisons (Operator Overloading).
  • std::format, std::span, <bit>, std::numbers, calendar and time zone support in <chrono>.
  • Designated initializers (Point{.x = 1, .y = 2}), consteval and constinit, constexpr containers inside compile-time code, abbreviated templates (void f(auto x)).
  • std::jthread with stop tokens, std::latch, std::barrier, std::counting_semaphore, atomic wait/notify.
  • contains() for associative containers, starts_with/ends_with for strings, std::erase/std::erase_if.
C++ C++20 in a few lines each

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This example sticks to C++20 on purpose: std::format builds strings, and std::puts prints them. In C++23 you'd simply write std::println, which is what the rest of this course uses.

C++23: finishing touches that matter

C++23 (finalized 2023, published 2024) completed much of what C++20 started:

  • std::print and std::println: formatted output straight to the console, fast and type-safe (Printing Output).
  • std::expected<T, E>: a value or an error, without exceptions, plus monadic and_then/transform/or_else on it and on std::optional (Error Handling Without Exceptions).
  • Deducing this: explicit object parameters (void f(this auto& self)) that remove const/non-const duplication and simplify CRTP (The this Pointer).
  • More ranges: std::ranges::to, views::zip, enumerate, chunk, slide, join_with, cartesian_product, and formatting of ranges with {}.
  • std::generator for coroutines, std::mdspan for multidimensional views, std::flat_map/std::flat_set (sorted vectors behind a map interface).
  • import std;: the whole standard library as one module.
  • Smaller items: std::string::contains, std::to_underlying, std::unreachable, std::byteswap, multidimensional operator[] (m[i, j]), if consteval, auto(x) decay-copies, size literals (10uz), [[assume(expr)]], #elifdef and #warning.
C++ C++23 features

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Not every compiler has every C++23 library feature yet. GCC 15 (our server) has nearly all of them except std::mdspan in our build, which is why the multidimensional arrays lesson shows it read-only. import std; works with recent GCC, Clang and MSVC, but needs build-system support; see C++20 Modules. Check your compiler's C++ status page before relying on the newest features in production.

Preview: C++26

C++26 is the next standard. Its feature set was frozen in 2025, and compilers are adding the features one by one, many only behind -std=c++26 (-std=c++2c on older versions). None of the code in this section runs in our editor, which compiles as C++23. The headline items:

Static reflection. Programs can inspect types at compile time and generate code from what they find, something C++ developers have wanted for decades. The ^^ operator produces a reflection of an entity, functions in std::meta query it, and a splice [: r :] turns a reflection back into code. Combined with expansion statements (template for), it makes tasks like enum-to-string conversion, serialization and command-line parsing possible without macros or code generators:

C++
// C++26 (read-only): convert any enum value to its name using reflection.
#include <meta>

template <typename E>
    requires std::is_enum_v<E>
constexpr std::string_view name_of(E value) {
    template for (constexpr auto e : std::define_static_array(std::meta::enumerators_of(^^E))) {
        if (value == [:e:]) {
            return std::meta::identifier_of(e);
        }
    }
    return "(unknown)";
}

enum class Color { Red, Green, Blue };
static_assert(name_of(Color::Green) == "Green");

Contracts. Functions can state preconditions and postconditions in their declarations, and contract_assert replaces the assert macro. What happens when a contract is violated (ignore, observe and log, or terminate) is chosen when you build, not in the source:

C++
// C++26 (read-only)
double safe_sqrt(double x)
    pre(x >= 0)
    post(result : result >= 0);

void transfer(Account& from, Account& to, Money amount) {
    contract_assert(amount > Money{0});
    // ...
}

More of C++26:

  • std::execution ("senders and receivers"): a standard model for asynchronous and parallel work with schedulers.
  • Pack indexing (Ts...[0]), #embed to include binary files as data, the placeholder variable _ that may be declared many times, and = delete("reason") with a message.
  • A hardened standard library: optional bounds checks on operator[] for vectors, spans and strings, and reading an uninitialized variable becomes erroneous behavior (a defined, diagnosable outcome) instead of undefined behavior.
  • Library additions such as std::inplace_vector (a fixed-capacity vector without heap allocation), saturation arithmetic (std::add_sat), std::linalg, std::hive, and std::span::at().

GCC 15 already implements several of the smaller items (pack indexing, #embed, _, = delete("...")) in -std=c++26 mode; reflection and contracts are arriving in the newest compiler releases and branches. Treat C++26 as "learn it now, use it when your compilers catch up".

How to modernize old code

When you meet pre-C++11 code, these replacements give the biggest wins with the least risk:

Old habit Modern replacement
new/delete, owning raw pointers std::vector, std::make_unique, std::make_shared
NULL or 0 for pointers nullptr
typedef using aliases
#define constants constexpr variables
Plain enum enum class
Iterator loops for (it = v.begin(); ...) Range-for, ranges algorithms
printf, sprintf, iostream formatting gymnastics std::format, std::print
Out parameters, magic error values Return structs, std::optional, std::expected
Function objects written as classes Lambdas
Copying to return big objects Return by value (moves and copy elision)
SFINAE and enable_if Concepts and requires

Turn on warnings (-Wall -Wextra) and tools like clang-tidy's modernize-* checks to find these automatically; the Compilers, Flags and Optimization lesson covers the flags.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which standard introduced lambdas, auto, move semantics and std::unique_ptr?

    C++11 is the "modern C++" baseline. C++14 then added std::make_unique and generic lambdas on top of it.
  2. 2. Your compiler says structured bindings auto [a, b] = p; need a newer standard. What is the minimum?

    Structured bindings, if with initializer, std::optional, std::variant and std::string_view all arrived in C++17.
  3. 3. Which group of features is from C++20?

    Concepts, ranges, coroutines and modules are C++20's big four. std::print and std::expected are C++23, lambdas are C++11, and reflection and contracts are C++26.
  4. 4. A program prints __cplusplus. Which value means it was compiled as C++20?

    The values encode the year and month of the standard. 202002 is C++20, 201703 is C++17, 202302 is C++23 and 199711 is C++98.
  5. 5. What is the best modern replacement for an owning raw pointer created with new?

    Smart pointers and containers make ownership explicit and free memory automatically, which removes leaks and double deletes.

Summary

  • C++11 is the modern baseline: auto, range-for, lambdas, move semantics, smart pointers, nullptr, enum class, constexpr, threads. C++14 polished it (make_unique, generic lambdas, digit separators).
  • C++17 added everyday conveniences: structured bindings, if with initializers, if constexpr, folds, CTAD, optional/variant/string_view, filesystem.
  • C++20 was a second revolution: concepts, ranges, coroutines, modules, <=>, std::format, std::span, designated initializers, jthread.
  • C++23 finished the job: std::print, std::expected, deducing this, ranges::to/zip/enumerate, std::generator, flat_map, import std;.
  • C++26 (preview) brings static reflection, contracts, std::execution and a hardened library.
  • Check versions with __cplusplus and feature-test macros from <version>, and modernize old code step by step.

Next: C++20 Modules, the language's replacement for header files, and what it takes to use them today.