In C++20, what is std::span, and how does a std::span<const float> parameter differ from const std::vector<float>&?
answer
- views, never owns
- pointer plus count
- any contiguous source
- const lives in the element type
basics
~20 sstd::span is a C++20 non-owning view of a contiguous sequence: in effect a pointer plus a count. A std::span<const float> parameter accepts a vector, std::array, C array or slice without copying, while a vector reference accepts only a vector.
solid answer
~40 s`std::span<T>` is a lightweight **view** over contiguous elements owned by someone else; a dynamic-extent span is essentially a pointer and a size, so you pass it by value. It replaces the `(const float* data, std::size_t n)` pair with one object whose length cannot disagree with its pointer. As a parameter, `std::span<const float>` accepts a `std::vector<float>`, a `std::array<float, N>`, a C array, another span, or a sub-range such as `std::span(track).subspan(2)`, all without copying, whereas `const std::vector<float>&` forces callers with other storage to build a vector first. Constness lives in the element type: `span<const float>` is read-only, `span<float>` lets the callee write. Because a span owns nothing, the owner must outlive it.
code
cpp · 23 lines#include <array>
#include <iostream>
#include <span>
#include <vector>
// Before: float peak(const float* data, std::size_t n);
float peak(std::span<const float> samples) {
float best = 0.0f;
for (float s : samples)
if (s > best) best = s;
return best;
}
int main() {
std::vector<float> track{0.1f, 0.9f, 0.4f};
std::array<float, 4> block{0.2f, 0.3f, 0.8f, 0.5f};
float raw[2] = {0.6f, 0.7f};
std::cout << peak(track) << ' ' // std::vector
<< peak(block) << ' ' // std::array
<< peak(raw) << ' ' // C array, size deduced
<< peak(std::span(track).subspan(2)) << '\n'; // the last element only
}go deeper
Recall that std::span is a C++20 non-owning view of contiguous elements, essentially a pointer and a size, and that it is passed by value.
Explain how one span parameter accepts vectors, std::array, C arrays and slices without copies, and why span<const T> rather than const span<T> expresses read-only access.
Use span to retire pointer-and-length parameters across an API while spelling out the lifetime contract: the caller's storage must outlive any span the callee keeps.
Decide where a codebase standardizes on span parameters versus container references, weighing caller flexibility against the lifetime discipline that non-owning views demand.
## What std::span is `std::span<T>` (header `<span>`, C++20) is a **view**: a small object that refers to a contiguous sequence of `T` owned by something else. The standard defines it as a view over a contiguous sequence of objects whose storage is owned by some other object. In practice a dynamic-extent span holds two things, a pointer to the first element and a count, and every member function runs in constant time. Because it owns nothing: - **Creating or copying a span never copies elements** and never allocates. Since C++23 the standard requires span to be trivially copyable, so passing it by value costs about as much as passing a pointer and a size. - **Destroying a span destroys nothing.** The owner, whether a `std::vector`, a `std::array`, a C array or a memory-mapped buffer, keeps the elements alive. - **The owner must outlive the span.** A span into storage that is freed or moved is a dangling view. ## The parameter it replaces Audio, graphics and networking code has long passed buffers as two parameters: ```cpp float peak(const float* data, std::size_t n); ``` That signature works with any contiguous storage, but nothing ties `n` to `data`: callers can pass the wrong length, swap arguments, or pass `vec.size()` alongside a different buffer. A span bundles the two: ```cpp float peak(std::span<const float> samples); ``` The callee iterates with range-based `for`, asks `samples.size()`, and takes sub-ranges with `first(n)`, `last(n)` or `subspan(offset, count)`, each returning another span without copying. ## Why not const std::vector<float>&? | parameter | accepts | cost | |---|---|---| | `const std::vector<float>&` | only a `std::vector<float>` with the default allocator | a reference; but callers with other storage must copy into a vector first | | `const float*` plus `std::size_t` | anything contiguous | two arguments that can disagree | | `std::span<const float>` | `std::vector`, `std::array`, a C array, another span, or a pointer and count | one small value; no copy of elements | A vector reference ties every caller to one container type and one allocator. A DSP routine called with a stack array, a `std::array` block, a slice of a larger vector, or a buffer owned by a C library would force a copy into a temporary vector. With `std::span<const float>`, all of these convert implicitly, and slicing a vector is `std::span(track).subspan(2)`. ## Const-correctness through the element type A span's constness lives in its **element type**, not in the span object: 1. `std::span<const float>` is a read-only view: the callee cannot modify the samples. Use it for inputs. 2. `std::span<float>` lets the callee write through it. Use it for output buffers such as `mix(std::span<float> out)`. 3. `const std::span<float>` is rarely useful: it stops reassigning the span, but elements are still writable. A `std::span<float>` converts implicitly to `std::span<const float>`, mirroring how `float*` converts to `const float*`. ## What span does not do - It does not own or extend lifetime. A span built from a temporary vector dangles once the full expression ends. - It does not resize. There is no `push_back`; the number of viewed elements is fixed when the span is built. - It is not a string view. Text gets `std::string_view`, which adds string operations; span is for any element type. - It does not check indexes in C++20 or C++23: `s[i]` with `i >= s.size()` is undefined behaviour. ## Migrating a pointer-and-length API A refactor of an audio library usually proceeds in small, safe steps: 1. Add a span overload beside the old function, `float peak(std::span<const float> samples)`, and implement the old signature by forwarding: `return peak(std::span(data, n));`. 2. Move callers over one at a time; containers and arrays convert implicitly, so most call sites shrink. 3. Replace manual offset arithmetic such as `data + 64, n - 64` with `samples.subspan(64)`. 4. Delete the pointer overload once nothing calls it. Output buffers follow the same path with `std::span<float>`. ## Common interview probes Expect follow-ups on passing by value (correct: it is a cheap view, no more than a pointer and a size), on `std::span<const T>` versus `const std::vector<T>&` (flexibility for callers), on what happens when the owner is destroyed (dangling), and on the static-extent form `std::span<T, N>`. A crisp answer says: non-owning, contiguous, pointer plus size, pass by value, replaces pointer-and-length pairs, and the owner must outlive it.
- Should a std::span parameter be passed by value or by const reference?By value. A span is a view of at most a pointer and a size, so copying it is as cheap as copying those two words, and passing by reference only adds an indirection. Constness that matters belongs in the element type: `std::span<const float>` for read-only input.
- Can a function taking std::span<float> be called with a const std::vector<float>?No. `std::span<float>` allows writing through it, and a const vector's elements are `const float`, so the conversion is rejected. Declare the parameter as `std::span<const float>` when the function only reads; a `std::span<float>` also converts implicitly to `std::span<const float>`.
A span is a bookmark plus a page count: it tells you where a passage starts and how long it is, but the book belongs to someone else, and if they throw it away the bookmark points at nothing.
- Says std::span copies the elements it is constructed from
- Thinks a span keeps its source vector alive
- Passes std::span<const float> by const reference out of habit
- Believes std::span can push_back or grow
- Says const std::span<float> makes the elements read-only
Assumes C++20, which added std::span; C++23 additionally requires span to be trivially copyable.