Access elements in std::string where positon of string is greater than its size

You have to consider the full specs.

First of all:

Expects: pos <= size().

If you dont follow the precondition you have undefined behaviour anyhow. Now...

Returns: *(begin() + pos) if pos < size(). Otherwise, returns a reference to an object of type charT with value charT(), where modifying the object to any value other than charT() leads to undefined behavior.

The only (valid) case that "otherwise" refers to is when pos == size(). And that is probably to emulate c string behaviour that have a some_string[size] element that can be accessed. Note that charT() is typically just '\0'.

PS: One might think that to implement the specification, operator[] would have to check if pos == size. However, if the underlying character array has a charT() at the end of the string, then you get the described behaviour basically for free. Hence, what seems a little different from "usual" access into an array is actually just that.


Statement 1 is the precondition for statement 2:

  1. Expects: pos <= size().

  2. Returns: *(begin() + pos) if pos < size().

    Otherwise (so here the only viable possibility is pos == size()), returns a reference to an object of type charT with value charT() (i.e. '\0'), where modifying the object to any value other than charT() leads to undefined behavior.

str[str.size()] basically points to the null-terminator character. You can read and write it, but you may only write a '\0' into it.


The operator expects pos to be less than or equal to size(), so if it is not less, then it is expected to be equal.