Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::span — a view over contiguous elements

std::span provides access to contiguous elements without owning them. It lets you pass a range together with its size, while subspan creates a view of part of that range without copying elements.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <span>
// Default construction is allowed only for extent 0 or std::dynamic_extent.
std::span<T> empty; // Extent defaults to std::dynamic_extent.
std::span<T> view{data, count};
view.size();
view.subspan(offset, count);
view.subspan<Offset, Count>();

std::span<T, Extent> from <span> is a view over contiguous elements. It neither owns those elements nor extends their lifetime. Extent specifies a fixed size in the type; the default std::dynamic_extent, as in std::span<T>, means the size is determined at runtime.

std::span::size() returns the element count as size_type, not the byte count. std::span::subspan(offset, count) creates a view starting at index offset without copying data. If count is omitted or explicitly set to std::dynamic_extent, the view covers the rest of the range. Otherwise, it covers count elements. This overload returns a dynamically sized view. subspan<Offset, Count>() takes template arguments. If Count != std::dynamic_extent, the result has fixed extent Count. If Count == std::dynamic_extent (whether supplied explicitly or defaulted), the result has dynamic extent when Extent == std::dynamic_extent and fixed extent Extent - Offset otherwise.

In C++23, offset <= size() is required and, for an explicit count other than std::dynamic_extent, so is count <= size() - offset. Violating these conditions causes undefined behavior, not a guaranteed exception. The template overload additionally rejects bounds incompatible with the extent encoded in the type. size() and subspan() have constant time complexity.

The data must remain valid while the view is used; destroying the owner or reallocating its storage can invalidate access. std::span<const T> prevents element modification through the view, whereas const std::span<T> does not. The example modifies the original array through a subview. The source is an evolving standard draft, so this description deliberately stays within operations available in C++23.

Examples

#include <iostream>
#include <span>

int main() {
    int values[]{10, 20, 30, 40};
    std::span<int> all{values};
    auto middle = all.subspan(1, 2);
    middle[0] = 25;

    std::cout << all.size() << ' ' << middle.size() << '\n';
    std::cout << values[1] << ' ' << middle[1] << '\n';
}

Result

4 2
25 30

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources