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?
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 valueCharT()
(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()
.