Ok, from cppreference
if pos < size(), or if pos == size() -> Returns a reference to CharT(), if the object referred by the returned reference is modified to any value other than CharT(), the behavior is undefined.
So, overall this code produces undefined behaviour, which just seems to be correct