std::span in C++20: Bounds-Safe Views for Sequences of Objects
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.
A std::span is an object that 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 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 its size (4).
The big three C++ compilers, MSVC, GCC, and Clang, support std::span.
Modernes C++ Mentoring
Do you want to stay informed: Subscribe.
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).
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 operations. A view does not own data, and it’s time to copy, move, and assignment it’s constant. Here is a quote from Eric Niebler’s 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 the 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 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, mapping each element to its square (3) only addresses these elements.
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.
What’s next?
Containers of the STL become more potent with C++20. For example, a std::string and std::vector can be created and 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: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery,and Matt Godbolt.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
My special thanks to Embarcadero | |
My special thanks to PVS-Studio | |
My special thanks to Tipi.build | |
My special thanks to Take Up Code | |
My special thanks to SHAVEDYAKS |
Modernes C++ GmbH
Modernes C++ Mentoring (English)
Rainer Grimm
Yalovastraße 20
72108 Rottenburg
Mail: schulung@ModernesCpp.de
Mentoring: www.ModernesCpp.org
Modernes C++ Mentoring,
Leave a Reply
Want to join the discussion?Feel free to contribute!