skip to content

Does indexing a C++ std::span check bounds, and what did C++26 change with std::span::at?

level: middleimportance: should knowfreq 36%

answer

  1. operator[] has a precondition
  2. no at() in C++20
  3. out_of_range arrives late
  4. hardened preconditions

basics

~10 s

No. std::span::operator[] has the precondition index < size(), and breaking it is undefined behaviour in C++20 and C++23. C++26 adds span::at(), which throws std::out_of_range, and makes operator[] a hardened precondition.

solid answer

~30 s

`std::span::operator[](i)` requires `i < size()` and does not check it: an out-of-range index is undefined behaviour in C++20 and C++23, exactly like a raw pointer. Unlike `std::vector` and `std::array`, span shipped without `at()`; C++26 adds `span::at(i)`, which throws `std::out_of_range` when `i >= size()`. The subview functions `first(n)`, `last(n)` and `subspan(offset, count)` have preconditions too. The C++26 draft marks these, along with `front()`, `back()` and `operator[]`, as **hardened preconditions**: a hardened implementation evaluates them with a terminating semantic, while a non-hardened one leaves violations undefined. Today, libc++'s hardening modes and libstdc++'s `_GLIBCXX_ASSERTIONS` add such checks as build options.

code

cpp · 18 lines
cpp
#include <cstdio>
#include <span>
#include <stdexcept>

int main() {
    float gains[3] = {0.5f, 0.8f, 1.2f};
    std::span<float> g(gains);

    std::printf("%g\n", g[1]);          // unchecked: i < size() is the caller's job
    try {
        std::printf("%g\n", g.at(7));   // C++26: checked, throws
    } catch (const std::out_of_range&) {
        std::printf("out_of_range\n");
    }
    auto tail = g.subspan(1);           // {0.8, 1.2}
    auto head = g.first(2);             // {0.5, 0.8}
    std::printf("%zu %zu\n", tail.size(), head.size());
}

go deeper

for a junior

Recall that span's operator[] is unchecked, like a pointer, and that an out-of-range index is undefined behaviour.

for a middle

Explain the preconditions of operator[], front, back, first, last and subspan, and contrast them with C++26's at(), which throws std::out_of_range.

for a senior

Choose where to validate: check lengths once where untrusted data enters, iterate rather than index in hot loops, and enable library hardening in test builds to catch violations.

for a principal

Decide whether a codebase enables library hardening in production, weighing the per-access cost against turning silent out-of-bounds reads into immediate terminations.

## The short answer by standard | operation | C++20 and C++23 | C++26 draft | |---|---|---| | `s[i]` with `i >= s.size()` | undefined behaviour (a precondition) | a **hardened precondition**: unchecked by default, checked by a hardened implementation | | `s.at(i)` | does not exist | throws `std::out_of_range` when `i >= size()` | | `s.front()`, `s.back()` on an empty span | undefined behaviour | hardened precondition | | `s.first(n)`, `s.last(n)`, `s.subspan(off, n)` out of range | undefined behaviour | hardened precondition | So `std::span`, like a raw pointer and `std::vector::operator[]`, does not check indexes in C++20 or C++23. The C++20 design kept span as cheap as a pointer and size; a checked accessor arrived only with C++26's `at()`. ## Why span had no at() at first `std::vector`, `std::array`, `std::deque` and `std::string` have long offered `at()`, which throws `std::out_of_range`. `std::span` shipped in C++20 without it, so the only bounds check was the one the caller wrote. C++26 added `span::at()` (paper P2821) for consistency with the other contiguous containers; libc++ implements it from release 18, and Apple clang 21 accepts it with `-std=c++2c` but rejects it under `-std=c++23` with `no member named 'at' in 'std::span<float>'`. The draft marks `at()` as freestanding-deleted, so freestanding implementations need not provide it. ## Preconditions and hardening A **precondition** is a condition the caller must make true before calling. If the caller breaks it, the behaviour is undefined: the library may read past the buffer, return garbage, or crash, and the optimizer may assume the violation never happens. The C++26 draft introduces **hardened preconditions** for a set of library functions, including span's `operator[]`, `front`, `back`, `first`, `last`, `subspan` and the static-extent conversions. On a hardened implementation, the condition is evaluated as a contract assertion with a terminating semantic before the function does anything else, so a violation ends the program; on a non-hardened implementation, a violation remains undefined behaviour. Implementations already ship opt-in checking for older standards. In libc++ it is selected with the `_LIBCPP_HARDENING_MODE` macro; in debug mode an out-of-range `s[5]` on a three-element span aborts with `libc++ Hardening assertion __idx < size() failed: span<T>::operator[](index): index out of range`, while fast mode traps without a message. libstdc++ has `_GLIBCXX_ASSERTIONS`. These are build options rather than language rules; the material on sanitizers and hardening flags covers choosing them. ## Subviews in practice The subview functions are how DSP and parsing code slices buffers without copying: - `first(n)`: the first `n` elements; precondition `n <= size()`. - `last(n)`: the last `n` elements; precondition `n <= size()`. - `subspan(offset, count)`: `count` elements starting at `offset`; precondition `offset <= size()` and, unless `count` is `std::dynamic_extent`, `count <= size() - offset`. Omitting `count` takes everything from `offset` to the end. Each returns a new span over the same storage; writing through a subspan of a `std::span<float>` writes the original buffer. ## Choosing a checking strategy 1. **Validate at the boundary.** Check lengths once where untrusted input enters, such as a decoded packet or a file header, then use unchecked `operator[]` in the inner loop. 2. **Prefer iteration over indexing.** A range-based `for` over a span cannot go out of bounds, and algorithms take the whole span. 3. **Use `at()` where an exception is the right failure mode** and the codebase is on C++26; otherwise write the explicit check. 4. **Turn on library hardening in testing builds**, and consider it in production where the per-access cost is acceptable. ## A worked example A gain table arrives from a configuration file as `std::span<const float> gains`, and a channel index comes from user input. Three ways to read it: - `gains[ch]` in C++23: correct only if `ch < gains.size()` was checked earlier; otherwise undefined behaviour that may read neighbouring memory silently. - `ch < gains.size() ? gains[ch] : 1.0f`: an explicit check with a fallback, valid in every standard. - `gains.at(ch)` in C++26: throws `std::out_of_range`, which suits code where an invalid index is a configuration error to report. The right choice depends on whether a bad index is a bug, an expected input error, or something to recover from. ## What interviewers listen for A good answer says plainly that `operator[]` is unchecked and an out-of-range index is undefined behaviour, that C++26 adds `at()` throwing `std::out_of_range`, that the subview functions have preconditions too, and that the C++26 hardened library and today's implementation hardening modes are how teams catch violations without changing code.

  • What are the preconditions of std::span::subspan(offset, count)?
    `offset <= size()`, and unless `count` is `std::dynamic_extent`, `count <= size() - offset`. Omitting `count` views everything from `offset` to the end. Violating either is undefined behaviour in C++23; in the C++26 draft both are hardened preconditions.
  • Why not simply call at() everywhere once a codebase is on C++26?
    `at()` checks on every access and reports failure by throwing, which some codebases cannot use, and the draft marks it freestanding-deleted. Validating lengths once at the boundary and iterating with range-for inside avoids per-access checks, while a hardened build catches mistakes in `operator[]` without changing call sites.

  • Says std::span::operator[] throws std::out_of_range
  • Believes span::at() is available in C++20
  • Thinks subspan clamps an oversized count to the available elements
  • Assumes a debug build always reports out-of-range span access
  • Says a hardened precondition makes violations well-defined everywhere

Assumes C++20/C++23 for unchecked operator[] and the C++26 draft (N5050) for span::at() and hardened preconditions; Apple clang 21 accepts at() only with -std=c++2c.