Do you run std :: string at '\ 0' when initialized with a string literal?

I know that string objects do not have null termination, but why should this work?

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

So, the constructor also copies the null delimiter, but doesn't increase the length? Why is this bothering?

+4
source share
2 answers

So the constructor also copies the null delimiter, but doesn't increase the length?

As you know, it std::stringdoes not contain a null character (and here it does not copy the null character).

, std::basic_string::operator[]. ++ 11, std:: basic_string:: operator [] , size().

pos == size(), CharT() ( ).

() undefined, , CharT().

+6

std::string C- , .

, "Hello, World!" :

std::string myString("Hello, World!");

// Internal Buffer...
// [ H | e | l | l | o | , |   | W | o | r | d | ! | \0 ]
//                                                   ^ Null terminator.

, std::string.

@songyuanyao , , myString[myString.size()]; '\0'.

, std::string ? , , '\0' :

std::string myString;
myString.size();              // 0
myString.push_back('\0');
myString.size();              // 1

std::string::c_str(). c_str() const char * . - , . ++ 11, .

P.S. , , , :

std::string S("Hey");
S.push_back('\0');
S.append("Jude");

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

// Only "Hey" is printed!
+2

Source: https://habr.com/ru/post/1661426/