Skip to content

Understand const semantics with std::span

std::span has different const behavior than containers: const applies to the span object, not necessarily the elements.

const std::span<int> span1; // const container, mutable elements
std::span<const int> span2; // mutable container, const elements
const std::span<const int> span3; // both const

Compare with:

const std::vector<int> vec; // Both container and elements are const
// Elements are const, span itself can be reassigned
void read_only(std::span<const int> data);
// Both span and elements are const
void truly_const(const std::span<const int> data);