Skip to content

std::span (C++20)

In a nutshell

A lightweight, non-owning view that safely references a contiguous sequence of memory, serving as a modern replacement for passing pointer-and-length arguments.

Header file

#include <span>

Core API Cheat Sheet

OperationSignatureDescription
Constructiontemplate<class T, size_t E = dynamic_extent> class spanTemplate class supporting static or dynamic extent
Get pointerT* data() constAccess underlying contiguous storage
Element countsize_t size() constReturns the number of elements
Byte sizesize_t size_bytes() constReturns the size of the sequence in bytes
Is emptybool empty() constChecks if the sequence is empty
Subscript accessreference operator[](size_t idx) constAccess specified element (no bounds checking)
First elementreference front() constAccess the first element
Last elementreference back() constAccess the last element
Take first Ntemplate<size_t C> constexpr span<element_type, C> first() constGet a sub-view of the first N elements
Take sub-viewtemplate<size_t O, size_t C> constexpr span<element_type, C> subspan() constGet a sub-view with specified offset and length

Minimal Example

cpp
// 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 Applicability: High

  • Zero-overhead abstraction: Contains only a pointer and a size (or compile-time constant size), with no heap allocation.
  • Perfect replacement for raw pointer parameters: Unifies the interface for arrays, std::array, and std::vector, improving safety.
  • TriviallyCopyable type: (Explicitly required since C++23, though mainstream implementations already satisfied this). It can be safely used for interrupt and DMA buffer operations.
  • size_bytes() and as_bytes(): Greatly simplify hardware register mapping and low-level byte-level 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

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05