Codectionary / Developer documentation / C++

C++ std::span views

C++20 std::span passes a contiguous sequence with its length without copying or owning the elements. A span can refer to an array or vector; changing elements through a mutable span changes the original storage.

Syntax

std::span<int> values; // #include <span>

Examples

C++ std::span views

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <span>
#include <iostream>
void doubleAll(std::span<int> values) {
    for (int& value : values) value *= 2;
}
int main() {
    int scores[] = {2, 3, 4};
    doubleAll(scores);
    std::cout << scores[0] << ' ' << scores[2] << '\n';
}
  1. Output: 4 8. The function receives a view of all three integers and edits the array in place.

Best practices

  • Keep the owner alive and avoid vector reallocation while a span exists. Use span<const T> for read-only access; unchecked indexing still requires a valid index.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading