Skip to content
Tutorials Center
My learning

Topics

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

std::bit_cast, mdspan and Newer Utilities

A tour of useful C++20 and C++23 library additions - std::bit_cast, bit utilities, byteswap, to_underlying, flat_map, move_only_function and mdspan for multidimensional views.

Each C++ standard adds a handful of small tools that quietly replace old, error-prone idioms. You have probably written a few of those idioms yourself: a memcpy to look at the bits of a float, a hand-rolled byte swap, a cast from an enum to its integer value, a function that multiplies a flat array by a width to simulate a matrix. The newer standards give each of these a name and a precise, safe meaning.

This lesson walks through the ones you are most likely to meet: std::bit_cast and the <bit> header, std::byteswap, std::to_underlying, std::flat_map, std::move_only_function, and std::mdspan, a multidimensional view that is part of C++23. Most examples run here with GCC 15 in C++23 mode. A few features are not available in this runner's standard library, and those appear as read-only code with a clear label. For the broader picture of what changed in each standard, see Modern C++ Features.

std::bit_cast: reinterpret bits without undefined behavior

Sometimes you really do need to look at an object's bits as a different type: show the exact bits of a float, hash a floating-point number, or read a binary format. The tempting way is a pointer cast:

C++
float f = 1.5f;
std::uint32_t bits = *reinterpret_cast<std::uint32_t*>(&f);   // undefined behavior

That breaks the aliasing rules, so the compiler is allowed to assume it never happens and may produce surprising code. The long-standing safe version copies the bytes with std::memcpy. Since C++20, std::bit_cast<To>(from) (header <bit>) does it directly: it creates a new object of type To whose bits are a copy of the source's. Both types must have the same size and be trivially copyable, and the compiler checks that. It is constexpr, so it even works at compile time.

C++ Looking at the bits of a float

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.

You can learn more about how floating-point numbers are stored in Floating-Point Numbers. The key point here: bit_cast is the sanctioned way to do type punning between unrelated trivially copyable types. It is not for pointers to non-trivial objects, and it does not apply to unions, which you read in structs and unions.

The toolbox

The same header holds a set of small functions for unsigned integers that used to need compiler-specific built-ins:

Function Meaning
std::popcount(x) number of 1 bits
std::has_single_bit(x) true if x is a power of two
std::bit_ceil(x) / std::bit_floor(x) smallest power of two >= x / largest <= x
std::bit_width(x) number of bits needed to represent x
std::countl_zero(x) / std::countr_zero(x) leading / trailing zero bits
std::rotl(x, n) / std::rotr(x, n) rotate bits left or right
std::byteswap(x) (C++23) reverse the byte order of an integer
std::endian little, big or native
C++ Bit tricks without compiler built-ins

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.

Use byteswap when you read or write binary formats with a fixed byte order, such as network protocols (see Network Programming Basics) and binary files. These functions only accept unsigned integer types, which keeps the results well defined; for background see Bitwise Operators.

std::to_underlying: enum to integer, with intent

Converting an enum to its underlying integer type used to require static_cast<std::underlying_type_t<E>>(e), which is long and repeats the type. C++23 adds std::to_underlying(e) in <utility>:

C++ to_underlying for scoped enums

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.

It works for any enum, scoped or not, and it reads as what it does. See Enums for scoped enum basics.

std::flat_map and flat_set (C++23)

std::map stores every entry in its own heap node. std::flat_map (header <flat_map>) keeps keys and values in two sorted contiguous containers, by default two std::vectors. Lookups use binary search over contiguous memory, which is very cache friendly, and iteration is fast. The trade-off is that inserting or erasing in the middle shifts elements, so it is best for data that is built once and read many times, or small maps. The interface matches std::map:

C++ flat_map: a map stored in sorted vectors

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.

Compared with std::map, a flat_map invalidates iterators on every insert and erase, like a vector. Pick it when you value speed of reads and a small memory footprint over cheap insertions.

std::move_only_function (C++23)

std::function requires the stored callable to be copyable. That excludes lambdas that capture a std::unique_ptr, a std::promise or other move-only objects. std::move_only_function (header <functional>) drops that requirement. It is the better type for task queues where each task runs once:

C++ Storing a lambda that owns a unique_ptr

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 same lambda would not compile inside a std::function. Note too that move_only_function supports const, noexcept and reference qualifiers in its signature, and calling an empty one is undefined behavior, so check it first.

std::mdspan: a multidimensional view (C++23)

You met std::span as a non-owning view over a one-dimensional range. std::mdspan (header <mdspan>) is its multidimensional cousin: it takes a pointer to flat data plus extents and lets you use m[row, col] syntax (C++23 allows several indices in operator[]) without copying or owning anything. A layout policy decides how indices map to memory: layout_right is row-major like C arrays, layout_left is column-major like Fortran, and layout_stride allows arbitrary strides for sub-views.

The runner's standard library does not provide <mdspan> yet, so the example below is read-only. It will compile with a library that implements C++23 mdspan, such as a recent libstdc++ or libc++ release, or with the reference implementation from the Kokkos project:

C++
#include <mdspan>
#include <print>
#include <vector>

int main() {
    std::vector<int> storage(2 * 3);           // 2 rows, 3 columns, stored flat
    std::mdspan grid(storage.data(), 2, 3);    // extents deduced: dynamic 2 x dynamic 3

    for (std::size_t r = 0; r < grid.extent(0); ++r) {
        for (std::size_t c = 0; c < grid.extent(1); ++c) {
            grid[r, c] = static_cast<int>(r * 10 + c);
        }
    }
    std::println("{}", storage);              // [0, 1, 2, 10, 11, 12]
}

What mdspan gives you is the indexing math, not storage. The same vector can be viewed as 2 x 3 or 3 x 2 or 6 x 1 without copying a byte. Until it is available in your toolchain, you can write a tiny stand-in that has the same idea, a flat vector plus width, which also shows what mdspan automates:

C++ A hand-written 2D view over flat data

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.

Which of these should you use?

flowchart TD
    Q["What do you need?"] --> A{"Read the bits of a value<br/>as another type?"}
    A -->|yes| B["std::bit_cast"]
    A -->|no| C{"Fixed byte order<br/>for a file or protocol?"}
    C -->|yes| D["std::byteswap + std::endian"]
    C -->|no| E{"Matrix or grid view<br/>over flat data?"}
    E -->|yes| F["std::mdspan"]
    E -->|no| G["See the summary table"]

A quick decision path for three of the tools in this lesson.

Library support differs between compilers and versions, so check your toolchain's documentation before relying on a C++23 feature, and test with the compiler you ship with. The feature-test macros (such as __cpp_lib_bit_cast, defined in <version>) tell you at compile time whether a feature exists.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is *reinterpret_cast<std::uint32_t*>(&f) for a float f a bad way to get its bits?

    Accessing a float through a pointer to an unrelated integer type breaks strict aliasing. std::bit_cast (or memcpy) is the defined way to do the same thing.
  2. 2. Which condition must hold for std::bit_cast<To>(from) to compile?

    The function copies the object representation, so sizes must match and both types must be trivially copyable.
  3. 3. What is the main advantage of std::move_only_function over std::function?

    std::function requires copyable callables. move_only_function only needs them to be movable, so it fits one-shot tasks that own resources.
  4. 4. std::mdspan owns the data it indexes.

    Like std::span, mdspan is a view. It stores a pointer and extents, and the storage must outlive it.
  5. 5. When is std::flat_map a good choice compared with std::map?

    flat_map keeps sorted keys and values in contiguous arrays, which makes lookups and iteration fast, but insertions shift elements and invalidate iterators.

Summary

  • std::bit_cast copies an object's bits into another trivially copyable type of the same size, safely and at compile time.
  • <bit> provides popcount, bit_width, bit_ceil, rotl, countr_zero, std::endian and (C++23) byteswap.
  • std::to_underlying turns an enum into its integer value without spelling the type.
  • std::flat_map stores a sorted map in contiguous vectors: great for read-heavy data.
  • std::move_only_function stores move-only callables such as lambdas that own a unique_ptr.
  • std::mdspan gives multidimensional indexing over flat memory without copying; check whether your library has it.

Next: Project: Grade Book, where you put the language together in a complete program.