Consider this code
string str;
cout << str[0] << str.size();
And what I get is not a run time error, but " 0"
, a 0
following a space. Why is this possible?
Consider this code
string str;
cout << str[0] << str.size();
And what I get is not a run time error, but " 0"
, a 0
following a space. Why is this possible?
str
is not uninitialized, it's default initalized as an empty std::string
; i.e. its size()
is 0
. And since C++11, the standard requires std::basic_string::operator[] to return a reference to the null character for this case.
If
pos == size()
, a reference to the character with valueCharT()
(the null character) is returned.
It's worth noting that before C++11, for the non-const version of operator[]
this is undefined behavior, for the const version a reference to null character will be returned; and since C++11 for the non-const version, any modification to other character on the returned reference is undefined behavior.
BTW: Undefined behavior means anything is possible; it has not to be a runtime error.