std::span
std::span
is a template class introduced in C++20 that provides a view of a contiguous sequence of elements, similar to a lightweight, non-owning reference. It represents a range over some contiguous storage, such as an array or a portion of a vector, without owning the underlying data.
The primary purpose of std::span
is to safely and efficiently pass arrays of data to functions without needing to pass the size explicitly, as the size information is encapsulated within the std::span
object. It can be considered a safer, more flexible alternative to raw pointer-and-size or pointer-and-length parameter passing.
Purpose and suitability
std::span
is a non-owning view of a contiguous sequence, often an array or a segment of another container. It is a lightweight, flexible, and safe way to refer to such sequences, ensuring no extraneous copies.
std::span
is best suited in the following scenarios:
- When a temporary view of data is needed
- When the underlying...