cpp20 · medium
C++20 std::span — Non-Owning Contiguous View
std::span<T> (C++20) is a lightweight, non-owning view over a contiguous sequence. It stores a pointer and a size (16 bytes on 64-bit), never copies data, and replaces raw (T*, size_t) parameter pairs with a safe, named type that carries its own size. It constructs implicitly from raw arrays, std::vector, std::array, and pointer+size pairs. span::subspan(offset, count) returns a new view into the same memory in O(1). span<T,N> with a static extent bakes the size into the type — sizeof = sizeof(ptr) only and size() is constexpr. Use span<const T> for read-only API contracts. Critical rule: a span NEVER outlives its owner — if the underlying vector reallocates, any span into it becomes a dangling pointer.
std::span<T> is a non-owning ptr+size pair over contiguous memory; it implicitly constructs from arrays, vectors, or {ptr,n}; subspan(offset,count) is O(1); span<T,N> bakes the size into the type; NEVER outlive the owner — span never copies.
The code
#include <span>
// std::span<T> = non-owning view over contiguous memory (ptr + size)// Dynamic extent (size at runtime)void process(std::span<int> s) { for (auto& x : s) x *= 2; // iterates safely // s.size() s.data() s[i] s.subspan(offset, count)}
// Static extent (size known at compile time)void fill_zeros(std::span<int, 4> s) { std::fill(s.begin(), s.end(), 0);}
int arr[6] = {10, 20, 30, 40, 50, 60};
// Implicit construction from array, vector, pointer+sizeprocess(arr); // full array: ptr=arr, size=6process({arr + 2, 3}); // subrange [2..4]: 30,40,50process(std::span{arr}.subspan(1, 4)); // subspan(offset, count)
std::vector<int> v = {1, 2, 3, 4};process(v); // works with vector too (contiguous)
// std::span NEVER copies — it IS a pointer+size pair// sizeof(span<int>) == 2 * sizeof(void*) (16 bytes on 64-bit)What this lesson walks through
- 01The problem std::span solves — (T*, size_t) pairs
- 02Full-array span — implicit construction from raw array
- 03Subrange span — view over part of the array
- 04subspan() — view-of-a-view, still zero copy
- 05Static extent span<T,N> — size baked into the type
- 06Works with vector, string, array — anything contiguous
- 07std::span golden rules for interviews
Before std::span, passing a buffer to a function meant passing a raw pointer and a separate size parameter. These are independent: nothing prevents you from passing size=100 for a 6-element array. std::span bundles pointer + size into a single named type with full iterator support.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of C++20 std::span — Non-Owning Contiguous View and 100+ animated C++ interview lessons.