2

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?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Eagle
  • 93
  • 5
  • 3
    `std::string()` is an empty string. See https://stackoverflow.com/questions/17738439/value-and-size-of-uninitialized-stdstring-variable-in-c. – Ry- Apr 03 '17 at 03:47
  • 1
    Also, even if you did something illegal, nothing guarantees that you will get a runtime error. What you would get is *undefined behavior*. – PaulMcKenzie Apr 03 '17 at 03:58
  • This is a gem of a question. Why so few upvotes? – P45 Imminent Apr 03 '17 at 16:59

1 Answers1

9

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 value CharT() (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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • And this is a gem of an answer! I think it's UB to attempt to modify the character through that reference. Is it worth adding that? – P45 Imminent Apr 03 '17 at 16:59
  • @P45Imminent I think I've mentioned it.. "Since C++11 any modification to other character on the returned reference is undefined behavior." – songyuanyao Apr 04 '17 at 12:45