Skip to content

std::span (C++20)

In a Nutshell

A lightweight, non-owning view that safely references a contiguous block of memory, replacing the traditional approach of passing a pointer paired with a length.

#include <span>

Core API Cheat Sheet

OperationSignatureDescription
Constructiontemplate<class T, size_t E = dynamic_extent> class spanTemplate class supporting static or dynamic extents
Get pointerT* data() constAccess the underlying contiguous storage
Element countsize_t size() constReturns the number of elements
Size in bytessize_t size_bytes() constReturns the size of the sequence in bytes
Check if emptybool empty() constChecks if the sequence is empty
Subscript accessreference operator[](size_t idx) constAccesses the specified element (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() constObtains a subview of the first N elements
Take subviewtemplate<size_t O, size_t C> constexpr span<element_type, C> subspan() constObtains a subview with the 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 a compile-time constant extent), with no heap allocation
  • Perfect replacement for raw pointer parameters: unifies interfaces for arrays, std::array, and std::vector, improving safety
  • TriviallyCopyable type (explicitly required since C++23, though mainstream implementations already satisfied this beforehand), safe to use for interrupt and DMA (Direct Memory Access) buffer operations
  • size_bytes() and as_bytes() greatly simplify hardware register mapping and low-level byte-level data processing

Compiler Support

GCCClangMSVC
TBATBATBA

See Also


Some content referenced from cppreference.com, licensed under CC-BY-SA 4.0

Built with VitePress