Understanding std::span

Written by on July 27, 2022 in C++, Programming with 0 Comments

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:

Example-1: span

Example-1: span

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:

Program Output

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.

Using span with Dynamic Allocation

Using span with Dynamic Allocation

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.

Program Output

Program Output

Another useful feature of span is being able to derive a subspan” from a given span. Here is an example:

Getting a subspan

Getting a subspan

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:

Checking subspan

Checking subspan

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!

Tags: ,

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *

Top