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)
    std::vector vec{1, 2, 3, 4, 5};     // (2)

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


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.

// 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.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". 


Rainer D 6 P2 540x540Modernes C++ Mentoring

Be part of my mentoring programs:





Do you want to stay informed about my mentoring programs: Subscribe via E-Mail.

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};    
    std::span span1(vec);                                 // (1) 
    std::span span2{span1.subspan(1, span1.size() - 2)};  // (2)
    std::transform(span2.begin(), span2.end(),            // (3)  
                   [](int i){ return i * i; });


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 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

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, Animus24, 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, and Rob North.


Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.



My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small


My special thanks to PVS-Studio PVC Logo


My special thanks to logo


My special thanks to Take Up Code TakeUpCode 450 60



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

Bookable (Online)


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++
  • C++20

Contact Me

Modernes C++,




Tags: span


0 #1 Johan Lundberg 2021-03-29 17:45
Thanks for the write-up. Question/comment: as far as I understand span is not bounds-safe. states that operator[] is undefined behaviour on out of bounds access.
0 #2 Rainer Grimm 2021-03-31 19:33
Quoting Johan Lundberg:
Thanks for the write-up. Question/comment: as far as I understand span is not bounds-safe. states that operator[] is undefined behaviour on out of bounds access.

I should clarify. I mean that std::span automatically deduces the size of a contiguous sequence of objects.

Stay Informed about my Mentoring



English 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

Course: The All-in-One Guide to C++20

Course: Master Software Design Patterns and Architecture in C++

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code


Today 1075

Yesterday 6503

Week 27332

Month 7578

All 12085787

Currently are 224 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments