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?
As you've known that
std::stringdoesn'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 tosize().