Modern C++ (C++11 to C++23)

C++11 changed the language so much that its creator, Bjarne Stroustrup, said it “feels like a new language”. Every three years since, a new standard has added features that make code safer, shorter and faster. This lesson collects the features that most change how everyday C++ is written: move semantics, compile-time computation, structured bindings, vocabulary types, ranges, std::format, three-way comparison and std::expected. Every example is a complete program; compile them with a C++20 compiler, and with C++23 mode for the last one.

The Standards at a Glance

The ISO committee publishes a new C++ standard every three years. Compilers implement features gradually, so check cppreference's compiler support tables before relying on a very recent one.

What Each Standard Added

StandardHeadline features
C++11Move semantics, auto, lambdas, range-based for, smart pointers, constexpr, nullptr, threads.
C++14Generic lambdas, relaxed constexpr (loops allowed), std::make_unique, digit separators.
C++17Structured bindings, if with initializer, std::optional, std::variant, std::string_view, parallel algorithms, <filesystem>.
C++20Concepts, ranges, coroutines, modules, <=>, consteval, std::format, std::span.
C++23std::expected, std::print, std::mdspan, deducing this, more ranges views, the standard library as a module (import std;).

This roadmap uses C++17 as the baseline. The C++20 and C++23 features below are widely supported by current GCC, Clang and MSVC releases; enable them with -std=c++20 (or -std=c++23) on GCC and Clang, and /std:c++20 (or /std:c++latest) on MSVC.

Move Semantics

Before C++11, returning or passing a large object by value meant copying it. Move semantics let an object hand its resources — heap memory, file handles, sockets — to another object, which is usually as cheap as copying a pointer.

Lvalues, Rvalues and std::move

An lvalue has a name and an address you can take, such as a variable. An rvalue is a temporary, such as the result of a function call, that is about to disappear. A move constructor takes an rvalue reference (T&&) and steals its contents. std::move does not move anything by itself: it is a cast that says “treat this lvalue as an rvalue, I no longer need its value”.

// Move semantics: transfer resources instead of copying them.
#include <iostream>
#include <utility>
#include <vector>

class Buffer {
public:
    explicit Buffer(std::size_t n) : data_(n, '.') {}

    // Copy: duplicate the contents (potentially expensive).
    Buffer(const Buffer& other) : data_(other.data_) { std::cout << "copy\n"; }

    // Move: take over the contents; the source stays valid but unspecified.
    Buffer(Buffer&& other) noexcept : data_(std::move(other.data_)) { std::cout << "move\n"; }

    std::size_t size() const { return data_.size(); }

private:
    std::vector<char> data_;
};

Buffer make_buffer() {
    Buffer b(1024);
    return b;                    // moved or elided entirely; never copied
}

int main() {
    Buffer a(1'000'000);
    Buffer b = a;                // a is an lvalue: copy
    Buffer c = std::move(a);     // std::move casts to an rvalue: move
    Buffer d = make_buffer();    // a temporary: moved or elided

    std::vector<Buffer> v;
    v.reserve(2);
    v.push_back(std::move(b));   // move into the container
    v.emplace_back(64);          // constructed in place: neither copy nor move

    std::cout << c.size() << ' ' << d.size() << ' ' << v.size() << '\n';
}

After a move, the source object is in a valid but unspecified state: you may assign to it or destroy it, but do not read its value. Mark move constructors noexcept; containers such as std::vector only use a move during reallocation when it cannot throw, and fall back to copying otherwise.

The Rule of Zero

If a class manages a resource directly, it needs the full set of special members — destructor, copy constructor, copy assignment, move constructor and move assignment (the rule of five). The better design is the rule of zero: build classes from members that already manage themselves (std::string, std::vector, std::unique_ptr), declare none of the special members, and let the compiler generate correct ones.

// Rule of zero: let members that already manage resources do the work.
#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct Order {
    std::string customer;                 // manages its own memory
    std::vector<int> items;               // manages its own memory
    std::unique_ptr<std::string> note;    // move-only ownership of an optional note
    // No destructor, copy or move members are declared: the compiler generates
    // correct moves, and copying is disabled automatically because of unique_ptr.
};

int main() {
    Order a{"Ana", {1, 2, 3}, std::make_unique<std::string>("gift wrap")};
    Order b = std::move(a);               // fine: memberwise move
    // Order c = b;                       // error: unique_ptr cannot be copied
    std::cout << b.customer << ' ' << b.items.size() << ' ' << *b.note << '\n';
}

Clearer Everyday Code

Several small features from C++11 to C++17 remove boilerplate and limit the scope of variables, which makes code easier to read and harder to get wrong.

Structured Bindings and if with Initializer

Structured bindings (C++17) give names to the parts of a pair, tuple, array or struct. if and switch statements can declare a variable that exists only within the statement, so a temporary result does not leak into the surrounding scope.

// C++17: structured bindings, and if statements with an initializer.
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> stock{{"keyboard", 12}, {"mouse", 0}};

    // Name the parts of a pair (or struct, or tuple) directly.
    for (const auto& [name, count] : stock) {
        std::cout << name << ": " << count << '\n';
    }

    // insert() returns {iterator, bool}; both get names, scoped to the if.
    if (auto [it, inserted] = stock.insert({"monitor", 3}); inserted) {
        std::cout << "added " << it->first << '\n';
    }

    // The variable `found` exists only inside this if statement.
    if (auto found = stock.find("mouse"); found != stock.end() && found->second == 0) {
        std::cout << "mouse is out of stock\n";
    }
}

Using auto Well

auto deduces a variable's type from its initializer. Use it where the type is obvious or unimportant — iterators, lambdas, results of make_unique — and to guarantee initialization, since an auto variable cannot be left uninitialized. Spell the type out where it carries meaning a reader needs, such as the units of a number. Remember that plain auto copies; write const auto& to avoid copying large elements in a loop.

Compile-Time Programming

Work done by the compiler costs nothing at run time and is checked before the program ever runs. Modern C++ steadily expanded what can be computed at compile time.

constexpr and consteval

A constexpr function may be evaluated at compile time when its arguments are constants, and runs normally otherwise. A consteval function (C++20) must be evaluated at compile time. static_assert checks a condition during compilation and stops the build if it is false.

// constexpr and consteval: move work from run time to compile time.
#include <array>
#include <iostream>

constexpr unsigned long long factorial(unsigned n) {
    unsigned long long result = 1;
    for (unsigned i = 2; i <= n; ++i) result *= i;   // loops are allowed since C++14
    return result;
}

consteval int square(int x) { return x * x; }         // C++20: compile time only

int main() {
    constexpr auto f10 = factorial(10);               // computed by the compiler
    static_assert(f10 == 3'628'800);                  // checked at compile time

    constexpr std::array<int, 3> sizes{square(2), square(3), square(4)};
    static_assert(sizes[2] == 16);

    unsigned n = 5;
    std::cout << f10 << ' ' << factorial(n) << ' ' << sizes[1] << '\n';  // run-time call works too
    // square(n);   // error: a consteval function needs a constant argument
}

Use constexpr for lookup tables, unit conversions and configuration values, so mistakes become compile errors. Together with templates and concepts from Templates & Generics, it replaces much of the preprocessor and template tricks of older C++.

Vocabulary Types

C++17 added standard types for situations that every codebase used to solve differently, with null pointers, magic values or unions.

optional, variant and string_view

  • std::optional<T> holds a value or nothing: a clear return type for “may not find a result”.
  • std::variant<A, B, C> holds exactly one of several types and knows which; std::visit calls the right handler, and the compiler checks that every alternative is handled.
  • std::string_view is a non-owning view of characters, cheap to pass by value, ideal for read-only string parameters. It must not outlive the string it refers to.
// C++17 vocabulary types: optional, variant and string_view.
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <variant>

// A result that may be absent, without a magic value or a null pointer.
std::optional<int> parse_port(std::string_view text) {
    if (text.empty()) return std::nullopt;
    int value = 0;
    for (char ch : text) {
        if (ch < '0' || ch > '9') return std::nullopt;
        value = value * 10 + (ch - '0');
        if (value > 65535) return std::nullopt;
    }
    return value;
}

// A value that is exactly one of several types, checked by the compiler.
using Setting = std::variant<int, double, std::string>;

struct Printer {
    void operator()(int v) const { std::cout << "int " << v << '\n'; }
    void operator()(double v) const { std::cout << "double " << v << '\n'; }
    void operator()(const std::string& v) const { std::cout << "text " << v << '\n'; }
};

int main() {
    std::cout << parse_port("8080").value_or(-1) << ' '
              << parse_port("80a").value_or(-1) << '\n';     // 8080 -1

    Setting timeout = 2.5;
    std::visit(Printer{}, timeout);                          // double 2.5
    timeout = std::string("off");
    std::visit(Printer{}, timeout);                          // text off
}

Ranges

C++20 ranges let algorithms take a whole container instead of a pair of iterators, and add views: lazy adaptors that filter, transform or slice a sequence without copying it. Views compose with the pipe operator, so a data pipeline reads from left to right.

Algorithms and Views

// C++20 ranges: algorithms on whole containers, and lazy, composable views.
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>

int main() {
    std::vector<int> prices{120, 15, 990, 42, 310, 7};

    std::ranges::sort(prices);                       // no begin()/end() pair needed

    // Views are lazy: nothing is computed until the loop pulls values.
    auto affordable_with_tax = prices
        | std::views::filter([](int p) { return p < 500; })
        | std::views::transform([](int p) { return p * 119 / 100; })
        | std::views::take(3);

    for (int p : affordable_with_tax) std::cout << p << ' ';   // 8 17 49
    std::cout << '\n';

    if (auto it = std::ranges::find(prices, 42); it != prices.end()) {
        std::cout << "found 42 at index " << (it - prices.begin()) << '\n';
    }
}

A view does not own its elements; it refers to the underlying container, so the container must outlive the view. The Algorithms & Lambdas lesson covers the classic algorithms that the std::ranges versions build on.

Formatting and Comparison

Two C++20 features remove large amounts of repetitive code: one for producing text, one for comparing values.

std::format and std::print

std::format builds strings from a format string with {} placeholders, like Python's str.format. It is type-safe, faster than std::ostringstream, and the format string is checked at compile time. C++23 adds std::print and std::println in <print>, which format and write directly to the console.

// C++20 std::format: type-safe formatting with a Python-like syntax.
#include <format>
#include <iostream>
#include <string>

int main() {
    std::string name = "keyboard";
    double price = 49.9;
    int qty = 3;

    std::cout << std::format("{:<10}|{:>8.2f}|{:>4}\n", name, price, qty);  // keyboard  |   49.90|   3
    std::cout << std::format("{0} x {1} = {2:.2f}\n", qty, price, qty * price);
    std::cout << std::format("hex {:#x}, binary {:08b}\n", 255, 5);
    // A format string that does not match its arguments, such as "{:d}" for a
    // std::string, is rejected at compile time.
}

Three-Way Comparison

Writing ==, !=, <, <=, > and >= by hand for every type is tedious and error-prone. The C++20 three-way comparison operator <=>, nicknamed the spaceship, can be defaulted to compare members in declaration order, and the compiler derives all six operators from it.

// C++20 three-way comparison: one defaulted operator provides all six comparisons.
#include <compare>
#include <iostream>
#include <set>

struct Version {
    int major = 0, minor = 0, patch = 0;
    auto operator<=>(const Version&) const = default;   // compares members in order
};

int main() {
    Version a{1, 9, 3}, b{1, 10, 0};
    std::cout << std::boolalpha << (a < b) << ' ' << (a == b) << ' ' << (b >= a) << '\n';

    std::set<Version> releases{{2, 0, 0}, {1, 10, 0}, {1, 9, 3}};   // ordered automatically
    std::cout << releases.begin()->minor << '\n';                    // 9
}

Errors Without Exceptions

Exceptions remain the standard way to report errors in C++, as covered in the Enterprise Development lesson. Some code cannot or should not use them: performance-critical paths, embedded systems built without exception support, or functions whose failures are common and expected, such as parsing user input.

std::expected

std::expected<T, E> (C++23) holds either a value of type T or an error of type E. It converts to true when it holds a value, and the error is available with .error(). Unlike std::optional, it tells the caller why something failed.

// C++23 std::expected: a value or an error, without exceptions.
#include <expected>
#include <iostream>
#include <string>

enum class ParseError { empty, not_a_number, out_of_range };

std::expected<int, ParseError> parse_percent(const std::string& text) {
    if (text.empty()) return std::unexpected(ParseError::empty);
    int value = 0;
    for (char ch : text) {
        if (ch < '0' || ch > '9') return std::unexpected(ParseError::not_a_number);
        value = value * 10 + (ch - '0');
        if (value > 100) return std::unexpected(ParseError::out_of_range);
    }
    return value;
}

int main() {
    for (std::string input : {"42", "", "7x", "250"}) {
        if (auto result = parse_percent(input)) {
            std::cout << input << " -> " << *result << "%\n";
        } else {
            std::cout << '"' << input << "\" -> error " << static_cast<int>(result.error()) << '\n';
        }
    }
}

Adopting Modern C++

Most real codebases mix code written for many standards. Modernize deliberately, with the compiler and tools helping.

A Note on Modules

C++20 modules replace textual #include with compiled interfaces (export module and import), which improves build times and stops macros leaking between files. C++23 adds import std; for the whole standard library. Compiler and build-system support has matured but still varies, so many projects keep headers for now; try modules in a new, small project with a recent CMake first.

Guidelines and Tools

  • Follow the C++ Core Guidelines, edited by Bjarne Stroustrup and Herb Sutter, for advice on writing modern C++.
  • Compile with high warning levels (-Wall -Wextra or /W4) and treat warnings as errors in CI.
  • Use clang-tidy's modernize-* checks to find and often fix old patterns automatically: raw new, NULL, explicit iterator loops, missing override.
  • Prefer the standard library over home-grown utilities, and smart pointers over raw owning pointers (see Memory & RAII).
  • Try small experiments on Compiler Explorer, which shows which compilers accept a feature and what code they generate.

Practice

Use a recent GCC, Clang or MSVC, or Compiler Explorer if nothing is installed.

Modernize Old Code

  1. Take an older program you wrote (or one from an earlier lesson) and replace raw owning pointers with std::unique_ptr, applying the rule of zero.
  2. Replace functions that return -1 or nullptr for “not found” with std::optional, and output built with << chains with std::format.
  3. Add a Buffer-style class that prints from its copy and move constructors, and predict, then verify, which one each line of your program calls.

Build a Small Pipeline

  1. Define a struct Product { std::string name; double price; int stock; } with a defaulted <=>, and fill a vector with ten products.
  2. With ranges views, print the names of the three cheapest products that are in stock, formatted in aligned columns with std::format.
  3. Write a parser that reads a product from a line of text and returns std::expected<Product, std::string>, then report every malformed line with its error.