Skip to content

std::span (C++20) ​

In a nutshell ​

A lightweight non-owning view that safely refers to a stretch of contiguous memory, replacing the traditional way of passing a pointer plus a length around.

Header file ​

#include <span>

Core API Cheat Sheet ​

OperationSignatureDescription
Constructiontemplate<class T, size_t E = dynamic_extent> class spanClass template supporting a static or dynamic length
Get pointerT* data() constAccesses the underlying contiguous storage
Element countsize_t size() constReturns the number of elements
Byte sizesize_t size_bytes() constReturns the number of bytes the sequence occupies
Is emptybool empty() constChecks whether the sequence is empty
Subscript accessreference operator[](size_t idx) constAccesses the element at the given index (no bounds checking)
First elementreference front() constAccesses the first element
Last elementreference back() constAccesses the last element
Take first Ntemplate<size_t C> constexpr span<element_type, C> first() constGets a subview of the first N elements
Take subviewtemplate<size_t O, size_t C> constexpr span<element_type, C> subspan() constGets a subview at the specified offset and length

Minimal Example ​

C++
// Standard: C++20
#include <iostream>
#include <span>

void print(std::span<const int> s) {
    for (int v : s) std::cout << v << ' ';
    std::cout << '\n';
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    std::span<int> s(arr);
    print(s);            // 1 2 3 4 5
    print(s.first(3));   // 1 2 3
    print(s.subspan(2)); // 3 4 5
}

Embedded Suitability: High ​

  • Zero-overhead abstraction: holds nothing but a pointer and a length (or a compile-time constant length), with no heap allocation
  • A perfect replacement for passing raw pointers around: unifies the interface of arrays, std::array, and std::vector, improving safety
  • A TriviallyCopyable type (explicitly required since C++23; mainstream implementations already satisfied this before that), safe to use in interrupt and DMA buffer operations
  • size_bytes() and as_bytes() greatly simplify mapping hardware registers and doing low-level byte-wise data processing

Compiler Support ​

GCCClangMSVC
To be addedTo be addedTo be added

See Also ​


Part of the content is referenced from cppreference.com and is licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05