skip to content

Besides the big four, which smaller C++20 additions — <=>, std::format, std::span and std::jthread — would you cite, and what did each replace?

level: juniorimportance: should knowfreq 55%

answer

  1. one operator, six comparisons
  2. type-safe braces instead of printf
  3. pointer plus length becomes one view
  4. joins itself and requests stop

basics

~10 s

A defaulted operator<=> generates all comparisons; std::format replaces printf and stream manipulators with type-safe {} formatting; std::span replaces pointer-and-length parameters; std::jthread replaces std::thread and joins automatically after requesting stop.

solid answer

~40 s

Declaring `auto operator<=>(const T&) const = default;` gives a class `<`, `>`, `<=` and `>=`, and implicitly a defaulted `==` (hence `!=`), replacing six hand-written operators. `std::format("{}: {:.2f}", name, price)` from `<format>` replaces `printf`'s type-unsafe varargs and `iostream` manipulators; the format string is checked at compile time. `std::span<const T>` from `<span>` replaces the `(T* data, size_t n)` parameter pair with one non-owning view of any contiguous sequence. `std::jthread` replaces `std::thread`: its destructor calls `request_stop()` and then `join()`, instead of calling `std::terminate`, and it passes a `std::stop_token` for cooperative cancellation. Designated initializers, `contains()` on associative containers, `starts_with` on strings and `std::erase_if` are other everyday C++20 wins.

code

cpp · 32 lines
cpp
#include <compare>
#include <concepts>
#include <format>
#include <iostream>
#include <ranges>
#include <span>
#include <string>
#include <thread>
#include <vector>

struct Version {
    int major, minor;
    auto operator<=>(const Version&) const = default;  // also gives ==, <, >, <=, >=
};

template <std::integral T>                              // concept as a constraint
T total(std::span<const T> values) {                    // any contiguous range, no copy
    T sum{};
    for (T v : values) sum += v;
    return sum;
}

int main() {
    std::vector<int> latencies{12, 7, 30, 5};
    auto slow = latencies | std::views::filter([](int ms) { return ms > 10; });
    std::cout << std::format("total={} slow={}\n", total<int>(latencies),
                             std::ranges::distance(slow));
    std::cout << std::format("{}\n", Version{1, 2} < Version{1, 10});
    std::jthread worker([](std::stop_token st) {
        while (!st.stop_requested()) std::this_thread::yield();
    });                                                 // destructor: request_stop() then join()
}

go deeper

for a junior

Know what each of the four does in one line and be able to write a defaulted <=> and a std::format call.

for a middle

Explain the details that bite: the implicit ==, comparison categories, span's non-owning lifetime and jthread's destructor calling request_stop then join.

for a senior

Describe replacing printf wrappers, pointer-length APIs or thread-join boilerplate in a real service, and the bugs that removed — terminate on a missing join, buffer overruns.

for a principal

Decide which of these to make house style once the baseline allows them, and what to enforce in review, such as span parameters for contiguous input.

## The additions that change daily code The big four get the headlines, but in a modernised service the C++20 features that touch the most lines are smaller ones. Interviewers ask about them because they reveal whether a candidate has written C++20 or only read about it. | Addition | Header | Replaces | Watch out for | |---|---|---|---| | defaulted `operator<=>` | `<compare>` | six hand-written comparison operators | comparison categories (`strong_ordering`, `weak_ordering`, `partial_ordering`) | | `std::format` | `<format>` | `printf` varargs, `iostream` manipulators, `snprintf` buffers | library support arrived late on some toolchains | | `std::span` | `<span>` | `(T* data, size_t n)` parameter pairs | non-owning: it can dangle | | `std::jthread` | `<thread>` | `std::thread` plus manual `join` and stop flags | the stop is cooperative | ## Three-way comparison The **spaceship operator** `<=>` returns an ordering object rather than a `bool`. Defaulting it compares members in declaration order: - `auto operator<=>(const Version&) const = default;` gives `<`, `>`, `<=` and `>=` through rewritten expressions; - when a class defaults `<=>` and declares no `==`, the compiler also declares a defaulted `==`, and `!=` is rewritten from it; - the result type tells callers what kind of ordering they have: `std::strong_ordering` for integers, `std::partial_ordering` for floating point, where NaN compares unordered. ## Formatting `std::format` brings Python-style replacement fields, `{}` and `{:>8.2f}`, to C++. Arguments are type-checked, the format string is checked at compile time when it is a constant, and user types become formattable by specialising `std::formatter`. It returns a `std::string`; C++23's `std::print` and `std::println` then write the same formatting straight to output. The replacement field carries the options: `{:>8}` right-aligns in eight characters, `{:08.3f}` zero-pads a floating-point value with three decimals, `{:x}` prints hexadecimal, and positional fields such as `{1} {0}` let a translated message reorder its arguments. A mismatch between a field and its argument, such as `{:d}` for a string, is a compile error for a constant format string. ## Span `std::span<T>` is a pointer and a length in one object, with a dynamic extent or a compile-time extent such as `std::span<int, 4>`. A function taking `std::span<const int>` accepts a `std::vector<int>`, a `std::array<int, N>` or a C array with no copy and no template. It is **non-owning**: a span over a temporary vector dangles once that vector is destroyed. ## Joining threads `std::thread`'s destructor calls `std::terminate` if the thread is still joinable, a common crash in code that forgets `join()` on an error path. `std::jthread` fixes that and adds cooperative cancellation: 1. its destructor calls `request_stop()` and then `join()` if the thread is joinable; 2. a callable whose first parameter is `std::stop_token` receives the thread's token; 3. the worker polls `stop_requested()` or registers a `std::stop_callback`; nothing interrupts it forcibly. ## Standard first, library later A modernisation story should say when each addition became usable, because the library pieces lagged the language. `std::format` is the clearest case: C++20 was finished in 2020, but libstdc++'s status page records text formatting as first shipped in GCC 13.1, and the libc++ status page records it in LLVM 14, with formatting of `<chrono>` types only in LLVM 21. Teams on older toolchains kept a third-party formatting library and switched to `std::format` once every compiler in their build shipped it. `<=>`, `std::span` and `std::jthread` were available earlier on most toolchains, so they are usually the first C++20 features a migrated codebase uses. A short before-and-after makes the point in an interview: ```cpp // C++17 void log_latency(const char* name, const int* samples, std::size_t n); std::printf("%s: %d ms ", name, samples[0]); // C++20 void log_latency(std::string_view name, std::span<const int> samples); std::cout << std::format("{}: {} ms ", name, samples[0]); ``` The C++20 signature cannot be called with a mismatched length, and the format call cannot pass an `int` where a string is expected without a compile error. ## Other C++20 conveniences worth naming - **Designated initializers**: `Config c{.retries = 3, .timeout_ms = 500};` for aggregates, in declaration order. - `map.contains(key)` instead of `find(key) != end()`. - `std::string::starts_with` and `ends_with`. - `std::erase` and `std::erase_if` instead of the erase-remove idiom. - `consteval`, `constinit`, `std::source_location`, `std::bit_cast` and the constants in `<numbers>`. Mentioning two or three of these, with the code they replaced, is usually more convincing than reciting the whole list.

  • Why does a defaulted <=> on a class with a double member return std::partial_ordering?
    With an `auto` return type, the defaulted operator returns the weakest comparison category among its members. `double`'s `<=>` returns `std::partial_ordering`, because NaN is unordered with every value, including itself. Callers then cannot assume that exactly one of `<`, `==` and `>` holds, which matters for sorting and for using the type as a map key.
  • Does std::jthread's stop request interrupt a blocked worker thread?
    No. `request_stop()` only sets the stop state and runs any registered `std::stop_callback`s. A worker blocked in a call that does not watch the token keeps waiting, and the destructor's `join()` waits with it. Make blocking waits stoppable, for example `std::condition_variable_any::wait` with a stop token, or register a callback that wakes the worker.

  • Defaulting operator<=> never gives the class an == operator.
  • std::span owns a copy of the elements it views.
  • std::jthread forcibly kills its thread when it goes out of scope.
  • std::format has the same type-safety problems as printf.
  • std::span works with std::list because it accepts any range.

Assumes C++20 for these additions, unchanged in C++23; std::print is the C++23 follow-up to std::format.