Introduced in C++20, std::span is a light-weight abstraction that provides a convenient view into a collection of contiguous elements. Note that it is not enough for the elements to be logically contiguous, but they must be contiguous in memory too. Thus, span will work with C-style arrays, C++ vectors and arrays. It will obviously not work with lists.
The primary benefit of using span is that it provides a unified interface to work with the different types of collection.
The following code is an example:
The function printElements takes a span<int> as argument and prints its elements. Even though this function is called in main with three different types of collections, span provides a common interface to access the respective elements.
Here is the program output:
The output is as expected.
The reason span is light-weight is because it does not own the collection.
It is also possible to work with dynamically allocated memory. The following example shows how we can use span along with unique_ptr. When constructing the span object, we additionally pass the element count.
span provides a convenient indexing operator “[]” to access individual elements of the collection it references. Note that we are able to modify the original collection through the span.
Here is the program’s output.
Another useful feature of span is being able to derive a “subspan” from a given span. Here is an example:
To further confirm that the subspan points to the second element (index: 1) of the original array, we compare the addresses. Look at the program’s output:
The output shows that the values match, and even the addresses agree. We can therefore conclude that the subspan is still a view into the original collection.
Thus, span can be convenient when working with contiguously stored collections.
That concludes our discussion of std::span.
Have a nice week!
Recent Comments