What is std::span in C++?
Introduced in C++20, std::span is a powerful class template defined in the <span> header, offering a non-owning view of a container in the C++ Standard Library. It serves as a safer alternative to using raw pointers and size information to represent a sequence of elements.
A span provides bounds-checked access to a contiguous group of elements, including arrays, strings, or vectors, without actually owning the data. Instead of holding separate pointers or iterators and length fields, a span unifies both into a single object, making it lightweight and efficient.
The primary focus of std::span is to enhance code safety and robustness. By using std::span, developers can avoid common pitfalls like null pointer dereferences and buffer overflows, contributing to more reliable and maintainable codebases.
Moreover, std::span is fully compatible with standard algorithms and interfaces that operate on contiguous data, making it seamlessly integrate into existing C++ codebases. As a result, adopting std::span can be a simple and effective way to improve code clarity and safety without sacrificing performance.
Code example
Here’s an example of creating and using an std::span:
#include <iostream>#include <span>#include<vector>void print(std::span<auto> ints) {for (const auto n : ints) {std::cout << n << " ";}std::cout << std::endl;}int main() {int arr[] = {1, 2, 3, 4, 5};char alphabets[] ={'a','b','c'};std::span<char> characters(alphabets);std::span<int> span(arr,5);print(span);print(characters);return 0;}
Code explanation
-
Line 2: This line includes the
<span>header, introduced in C++20, providing thestd::spanclass template. -
Lines 5–10: The
printfunction is declared, which takes anstd::spanas a parameter. The use ofconst autoin the template parameter ensures that the function works with bothstd::span<T>andstd::span<const T>. -
Line 16: The first span,
characters, is initialized with thealphabetsarray, creating a span of characters. Note that thisstd::span<char>does not include the null-terminator ofalphabets, making it suitable for working with raw character data. -
Line 17: An
std::span<int>object namedspanis created, which references thearrarray. Thespancovers the entire array, and the second argument (5) specifies the number of elements in the array. -
Lines 19–20: These lines call the
printfunction, passing thespanandcharactersspans as arguments. Theprintfunction prints the elements of each span, demonstrating howstd::spanenables seamless iteration over different types of sequences.
The key advantage of std::span is its ability to work with sequences of elements without copying or transferring ownership. As a non-owning view, it provides a uniform interface for accessing the elements, allowing us to treat arrays, containers, and other sequences interchangeably. It is particularly useful in function parameters, where we can pass std::span instead of raw pointers or containers, enabling safer and more efficient function calls.
Note: The
std::spanclass template provides various member functions and operators to access and manipulate the elements, such assize(),operator[],front(),back(), etc. Additionally,std::spansupports slicing to create sub-spans and allows us to convert between spans of different element types, making it a versatile tool for working with contiguous data in C++.
Free Resources