Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 171 ยท Arrays and Vectors

std::span

Learn std::span (C++20) - one function for C arrays, std::array and std::vector, read-only vs writable spans, subspan, fixed vs dynamic extent, and dangling-span pitfalls.

Suppose you write a function that averages some numbers. Should it take a std::vector<double>? Then it can't be called with a std::array or a C array. A template on the container type? That works, but it's more machinery than the problem needs. The C way, a pointer plus a length, accepts everything but is easy to call wrong, and nothing stops you from passing the wrong length.

C++20's std::span solves this cleanly. A span is a view: a lightweight object that refers to a sequence of elements stored contiguously somewhere else, holding only a pointer to the first element and a count. It owns nothing and copies nothing. Any contiguous sequence (a std::vector, a std::array, a C array, or a part of any of them) converts to a span automatically, so one function signature serves them all. If you've read std::string_view, you already know the idea: std::span is the same thing for arbitrary element types.

One function for every contiguous container

Include <span> and write the parameter as std::span<const T> when the function only reads the elements:

C++ One function, many containers

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.

Every call site passes its container directly; the conversion to std::span<const double> is implicit. Inside average, values behaves like a small container: it has size(), empty(), [] and works with range-based for and the standard algorithms. The {week.data() + 5, 2} call builds a span from a pointer and a count (the last two days), which is how you wrap a buffer coming from a C API. {} is an empty span.

What doesn't convert: containers that aren't contiguous. A std::list or std::map keeps its elements in separate nodes, so there is no single pointer-plus-size to describe them, and passing one to average is a compile error. For those, write a template over ranges (Ranges and Views).

Read-only and writable spans

The element type of the span decides what the function may do:

  • std::span<const T> promises not to modify the elements. It accepts both mutable and const containers. Use it for any function that only reads.
  • std::span<T> lets the function modify the original elements in place. It only accepts non-const containers, because a span over a const vector can't hand out writable access.

Modifying through a span changes the caller's data, because there is no copy:

C++ Writing through a span

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 changes show up in signal, pixels and levels because the functions wrote straight into their memory. std::span(levels).last(3) passes a view of only the last three elements, so the first three keep their out-of-range values. Uncomment the clamp_all(fixed, ...) line to see the compiler refuse a writable span over const data.

What a span can do

Member Meaning
size(), size_bytes() Number of elements, and that count ร— sizeof(T)
empty() Whether size() is 0
s[i] Element i, unchecked (UB if out of range)
front(), back() First and last element (UB on an empty span)
data() Pointer to the first element
begin(), end() Iterators, so loops and algorithms work
first(n), last(n) A span of the first or last n elements
subspan(offset, count) A span of count elements starting at offset (count defaults to "the rest")

Two things are missing compared with a vector. There is no push_back or erase, because a span can't change the size of memory it doesn't own. And in C++20 and C++23 there is no checked at(): indexing is unchecked, and first, last and subspan with counts that are too large are undefined behavior too. C++26 adds span::at(). Until then, check sizes yourself, as the next example does.

Slicing with first, last and subspan

Slicing a span is free: it just makes a new pointer-and-size pair over the same memory. That makes spans ideal for code that processes a buffer piece by piece, such as parsing a message with a fixed-size header followed by a body:

C++ Parsing a buffer with subspan

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.

parse never copies a byte: header, payload and the loop all look at the vector's memory. Each slice is guarded by a size check first, because subspan beyond the end would be undefined behavior. The chunk loop shows a common pattern: keep a span of "what's left" and shrink it from the front with subspan(n) until it's empty. The last chunk has only two elements thanks to std::min.

Fixed and dynamic extent

std::span has a second, optional template parameter: the extent, meaning the number of elements, if it's known at compile time.

  • std::span<T> is short for std::span<T, std::dynamic_extent>. The size is stored at runtime. This is what you use 95% of the time.
  • std::span<T, N> has a fixed extent: it always refers to exactly N elements, the size is part of the type, and the span doesn't need to store it.

A fixed extent documents and enforces a requirement. A function taking std::span<const float, 3> accepts a std::array<float, 3> or a float[3], but a std::array<float, 4> is a compile error:

C++ Fixed vs dynamic extent

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 lengths are 13, 3 and 7. first<3>() (with the count as a template argument) returns a fixed-extent span, so it fits length; the runtime version first(3) returns a dynamic span, which wouldn't. A fixed-extent span is only a pointer, 8 bytes on our server, while a dynamic one also stores its size, 16 bytes. Converting from fixed to dynamic is always safe and implicit. Going the other way, std::span<const float, 3>{some_dynamic_span} must be written explicitly, and if the sizes don't match the behavior is undefined.

Viewing the raw bytes

std::as_bytes(span) turns any span into a std::span<const std::byte> over the same memory, and std::as_writable_bytes does the same for writable spans. This is the standard way to hand data to hashing, networking or file APIs that think in bytes:

C++
std::array<std::uint16_t, 2> words{0x0102, 0x0304};
for (std::byte b : std::as_bytes(std::span(words))) {
    std::print("{:02x} ", std::to_integer<int>(b));   // 02 01 04 03 on x86
}

The byte order depends on the processor's endianness; most desktop and server CPUs are little-endian, which stores the low byte first. Binary Files explains why that matters for portable file formats.

Spans don't own: dangling spans

A span is only as valid as the memory it points to. Like std::string_view, it can outlive its data, and then reading through it is undefined behavior:

C++
std::vector<int> make_scores();

std::span<const int> bad = make_scores();   // the vector is a temporary...
std::println("{}", bad[0]);                 // ...destroyed at the end of the line: UB

std::vector<int> v{1, 2, 3};
std::span<int> view = v;
v.push_back(4);                              // may reallocate the vector's memory
view[0] = 10;                                // UB if it did: view points to freed memory

The second case is the iterator invalidation problem again: any operation that can reallocate a vector invalidates spans over it, just as it invalidates pointers and iterators.

Safe habits:

  • Use spans mainly as function parameters. The caller's container is alive for the whole call, so the span can't dangle.
  • Be careful storing spans in variables or struct members. Make sure the data outlives the span and doesn't reallocate meanwhile.
  • Never return a span to a local container from a function. Return the container itself.

When to use a span

  • Function reads a sequence of T โ†’ std::span<const T>. Pass it by value: it is just two words, so copying it is as cheap as passing a reference.
  • Function modifies elements in place but doesn't add or remove them โ†’ std::span<T>.
  • Function must add or remove elements โ†’ std::vector<T>&, since a span can't change the size.
  • Text โ†’ std::string_view, which adds string operations like find and substr.
  • Non-contiguous containers (std::list, std::set) โ†’ a template over ranges.
  • The function stores the data for later โ†’ take ownership with a std::vector<T> parameter instead.

Parameters: by Value, by Reference and by const Reference places spans in the bigger picture of how to pass data to functions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a dynamic-extent std::span<int> actually store?

    A span is a view, typically two words, a pointer and a size. Fixed-extent spans store only the pointer because the size is in the type.
  2. 2. void scale(std::span<double> s) doubles every element. You call scale(v) with std::vector<double> v{1, 2}. What is v afterwards?

    A span refers to the vector's own memory, so writing through it modifies v. Use std::span<const double> when a function must not modify anything.
  3. 3. Which argument can NOT be passed to a std::span<const int> parameter?

    A span needs contiguous storage. A std::list stores its elements in separate nodes, so it has no single pointer and size to describe them.
  4. 4. With std::vector<int> v{1, 2, 3, 4, 5};, what does std::span(v).subspan(1, 3) refer to?

    subspan(offset, count) starts at index 1 and takes 3 elements, so it views 2, 3 and 4 without copying them.
  5. 5. Why is this a bug? std::span<int> s = v; v.push_back(6); std::println("{}", s[0]);

    Spans don't own their data. Anything that can reallocate the vector invalidates spans, pointers and iterators into it, so reading s[0] afterwards is undefined behavior.

Summary

  • std::span<T> (C++20, <span>) is a non-owning view of a contiguous sequence: a pointer plus a size.
  • C arrays, std::array, std::vector and pointer-plus-count all convert to a span, so one function handles them all; non-contiguous containers don't.
  • std::span<const T> is for reading; std::span<T> writes into the caller's elements. Pass spans by value.
  • first, last and subspan slice without copying; indexing and out-of-range slices are unchecked (C++26 adds at()).
  • std::span<T, N> has a fixed extent checked at compile time; first<N>() produces one from a dynamic span.
  • std::as_bytes views any span as raw bytes.
  • A span dangles if its data dies or reallocates; use spans mostly as parameters.

Next: Functions, where you'll learn to define, declare and call your own functions, the building blocks of every C++ program.