Is it bad to depend on index 0 of an empty std::string?

C++14

No; you can depend on it.

In 21.4.5.2 (or [string.access]) we can find:

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

In other words, when pos == size() (which is true when both are 0), the operator will return a reference to a default-constructed character type which you are forbidden to modify.

It is not special-cased for the empty (or 0-sized) strings and works the same for every length.


C++03

And most certainly C++98 as well.

It depends.

Here’s 21.3.4.1 from the official ISO/IEC 14882:

Returns: If pos < size(), returns data()[pos]. Otherwise, if pos == size(), the const version returns charT(). Otherwise, the behavior is undefined.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)