The relevant section in the standard is §21.4.5:
const_reference operator[](size_type pos) const noexcept;
reference operator[](size_type pos) noexcept;
[...]
Returns: *(begin() + pos)
if pos < size()
, otherwise a reference to an
object of type T
with value charT()
; the referenced value shall not be modified.
If I understand this correctly, it means that as long as the index given to operator[]
is smaller than the string's size
, one is allowed to modify the value. If however, the index is equal to size
and thus we obtain the \0
terminating the string, we must not write to this value.
Cppreference uses a slightly different wording here:
If pos == size(), a reference to the character with value CharT()
(the null character) is returned.
For the first (non-const) version,the behavior is undefined if this character is modified.
I read this such that 'this character' here only refers to the default constructed CharT
, and not to the reference returned in the other case. But I admit that the wording is a bit confusing here.