What is the rationale for std::span::operator[] being explicitly undefined for out of bounds access?
00:55 26 May 2026

Triggered by this question I was reading about out of bounds access via std::span::operator[] here:

If idx < size() is false, the behavior is undefined.(until C++26)

Why is it specified explicitly to be undefined?

With


std::span s{ptr,size};

I see two cases:

  • The underlying array has only s.size() elements, attempting to call s[s.size()] is undefined, because ptr[size] is undefined. That span::operator[] is specified to be undefined does not actually change that.

  • The underlying array has more than s.size() elements. In that case s.data()+size can be dereferenced without problem, yet s[s.size()] is undefined.

What is the rationale of making span::operator undefined for elements that can be reached via span::data() ?

c++