Unfortunately, this is UB, if I interpret the wording correct (in any case, it’s not allowed):
§21.4.5 [string.access] p2
Returns:
*(begin() + pos)
ifpos < size()
, otherwise a reference to an object of typeT
with valuecharT()
; the referenced value shall not be modified.
(Editorial error that it says T
not charT
.)
.data()
and .c_str()
basically point back to operator[]
(§21.4.7.1 [string.accessors] p1
):
Returns: A pointer
p
such thatp + i == &operator[](i)
for eachi
in[0,size()]
.