c++stringnull-terminatedsubscript-operator

Do std::strings end in '\0' when initialized with a string literal?


I know string objects aren't null terminated but why should this work?

std::string S("Hey");
for(int i = 0; S[i] != '\0'; ++i)
   std::cout << S[i];

So the constructor copies the null terminator as well, but does not increment the length? Why does it bother?


Solution

  • So the constructor copies the null terminator as well, but does not increment the length?

    As you've known that std::string doesn't contain the null character (and it doesn't copy the null character here).

    The point is that you're using std::basic_string::operator[]. According to C++11, std::basic_string::operator[] will return a null character when specified index is equivalent to size().

    If pos == size(), a reference to the character with value CharT() (the null character) is returned.

    For the first (non-const) version, the behavior is undefined if this character is modified to any value other than charT().