std::span in C++20: Bounds-Safe Views for Sequences of Objects

Contents[Show]

In my seminar, I often hear the question: How can I safely pass a plain array to a function? With C++20, the answer is quite easy: Use a std::span.

TimelineCpp20CoreLanguage

 

A std::span stands for an object than can refer to a contiguous sequence of objects. A std::span, sometimes also called a view, is never an owner. This contiguous memory can be a plain array, a pointer with a size, a std::array, a std::vector, or a std::string. A typical implementation consists of a pointer to its first element and a size. The main reason for having a std::span<T> is that a plain array will be decay to a pointer if passed to a function; therefore, the size is lost. This decay is a typical reason for errors in C/C++.

Automatically deduces the size of a contiguous sequence of objects

In contrast, std::span<T> automatically deduces the size of contiguous sequences of objects.

 

// printSpan.cpp

#include <iostream>
#include <vector>
#include <array>
#include <span>

void printMe(std::span<int> container) {
    
    std::cout << "container.size(): " << container.size() << '\n';  // (4)
    for(auto e : container) std::cout << e << ' ';
    std::cout << "\n\n";
}

int main() {
    
    std::cout << std::endl;
    
    int arr[]{1, 2, 3, 4};              // (1)
    printMe(arr);
    
    std::vector vec{1, 2, 3, 4, 5};     // (2)
    printMe(vec);

    std::array arr2{1, 2, 3, 4, 5, 6}; // (3)
    printMe(arr2);
    
}

 

The C-array (1), std::vector (2), and the std::array (3) have int's. Consequently, std::span also holds int's. There is something more interesting in this simple example. For each container, std::span can deduce it's size (4).

All of the big three C++ compilers MSVC, GCC, and Clang, support std::span.

printSpan

 

There are more ways to create a std::span.

Create a std::span from a pointer and a size

You can create a std::span from a pointer and a size.

// createSpan.cpp

#include <algorithm>
#include <iostream>
#include <span>
#include <vector>

int main() {

    std::cout << std::endl;
    std::cout << std::boolalpha;

    std::vector myVec{1, 2, 3, 4, 5};
	
    std::span mySpan1{myVec};                                        // (1)
    std::span mySpan2{myVec.data(), myVec.size()};                   // (2)
	
    bool spansEqual = std::equal(mySpan1.begin(), mySpan1.end(),
                                 mySpan2.begin(), mySpan2.end());
	
    std::cout << "mySpan1 == mySpan2: " << spansEqual << std::endl;  // (3)

    std::cout << std::endl;
	
}

 

As you may expect, the from a std::vector created mySpan1 (1) and the from a pointer and a size created mySpan (2)  are equal (3).

createSpan

 

You may remember that a std::span is sometimes called a view.Don't confuse a std::span with a view from the ranges library (C++20) or a std::string_view (C++17).

A view from the ranges library is something that you can apply on a range and performs some operation. A view does not own data, and it's time to copy, move, assignment it's constant. Here is a quote from Eric Nieblers range-v3 implementation, which is the base for the C++20 ranges: "Views are composable adaptations of ranges where the adaptation happens lazily as the view is iterated." These are all my posts to then ranges library: category ranges library

A view (std::span) and a std::string_view are non-owning views and can deal with strings. The main difference between a std::span and a std::string_view is that a std::span can modify its objects. When you want to read more about std::string_view, read my previous post: "C++17 - What's New in the Library?" and "C++17 - Avoid Copying with std::string_view". 

Modifying its objects

You can modify the entire span or only a subspan. When you modify the span, you modify the referenced objects..

The following program shows how a subspan can be used to modify the referenced objects from a std::vector.

// spanTransform.cpp

#include <algorithm>
#include <iostream>
#include <vector>
#include <span>

void printMe(std::span<int> container) {
    
    std::cout << "container.size(): " << container.size() << std::endl;
    for(auto e : container) std::cout << e << ' ';
    std::cout << "\n\n";
}

int main() {
    
    std::cout << std::endl;
    
    std::vector vec{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};    
    printMe(vec);
    
    std::span span1(vec);                                 // (1) 
    std::span span2{span1.subspan(1, span1.size() - 2)};  // (2)
    
                                                 
    std::transform(span2.begin(), span2.end(),            // (3)  
                   span2.begin(), 
                   [](int i){ return i * i; });
    
    
    printMe(vec);                                       
    
}

 

span1 references the std::vector vec (1). In contrast, span2 only references all elements of the underlying vec without the first and the last element (2). Consequently, the mapping of each element to its square (3) only addresses these elements. 

spanTransform

There are many convenience functions to refer to the elements of the span.

Addressing the elements of a std::span

The table presents the functions to refer to the elements of a span.

 

Function  Description
 span.front() Access the first element
 span.back() Access the last element
 span[i] Access the i-th element
 span.data() Returns a pointer to the beginning of the sequence 
 span.size() Returns the number of elements of the sequence
 span.size_bytes() Returns the size of the sequence 
 span.empty() Returns if the sequence is empty

span<count>.first()

span.first(count)

Returns a subspan consisting of the first count elements of the sequence

span<count>last()

span.last<count>

Returns a subspan consisting of the last count elements of the sequence

span<first, count>.subspan()

span.subspan(first, count)

Returns a subspan consisting of count elements starting at first

 

The small program shows the usage of the function subspan.

// subspan.cpp

#include <iostream>
#include <numeric>
#include <span>
#include <vector>

int main() {

    std::cout << std::endl;

    std::vector<int> myVec(20);
    std::iota(myVec.begin(), myVec.end(), 0);                   // (1)
    for (auto v: myVec) std::cout << v << " ";

    std::cout << "\n\n";

    std::span<int> mySpan(myVec);                               // (2)
    auto length = mySpan.size();

    auto count = 5;                                             // (3)
    for (long unsigned int first = 0; first <= (length - count); first += count ) {
        for (auto ele: mySpan.subspan(first, count)) std::cout << ele << " ";
        std::cout << std::endl;
    }

}

 

The program fills the vector with all numbers from 0 to 19 (1), and initializes a std::span with it (2). The algorithm std::iota fills myVec with the sequentially increasing values, starting with 0. Finally, the for-loop (3) uses the function subspan to create all subspans starting at first and having count elements until mySpan is consumed.

subspan

What's next? 

Containers of the STL become with C++20 more powerful. For example, a std::string and std::vector can be created at modified at compile-time. Further, thanks to the functions std::erase and std::erase_if, the deletion of the elements of a container works like a charm.

 

 

Thanks a lot to my Patreon Supporters: Meeting C++, Matt Braun, Roman Postanciuc, Venkata Ramesh Gudpati, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Darshan Mody, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Wolfgang Gärtner, Jon Hess, Christian Wittenhorst, Louis St-Amour, Stephan Roslen, Venkat Nandam, Jose Francisco, Douglas Tinkham, Lakshman, Kuchlong Kuchlong, Avi Kohn, Serhy Pyton, Robert Blanch, Kuma [], Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, and Kai.

 

 

Seminars

I'm happy to give online-seminars or face-to-face seminars world-wide. Please call me if you have any questions.

Standard Seminars 

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

Contact Me

Modernes C++,

RainerGrimmSmall

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 5015

Yesterday 5047

Week 5015

Month 144776

All 4594868

Currently are 198 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments