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.
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.
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.
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.
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.
|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|
|Returns a subspan consisting of the first count elements of the sequence|
|Returns a subspan consisting of the last count elements of the sequence|
|Returns a subspan consisting of count elements starting at first|
The small program shows the usage of the function subspan.
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.
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, Kris Kafka, 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, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, 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, and Bhavith C Achar.
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|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,