What is the difference between these two different initializations for a string in C ++?

Source

#include <iostream> #include <string> using namespace std; int main(){ std::string s{'a', 'b', '\0', 'c'}; std::string s1="ab\0c"; cout<<s.size()<<" "<<s<<endl; cout<<s1.size()<<" "<<s1<<endl; return 0; } 

and the way out is

 4 abc 2 ab 

I wonder why this phenomenon occurs and is there a difference between the two types of initialization in C ++? Thanks.

+5
source share
2 answers

For s you correspond to a constructor that accepts a list of character initializers: this is (9) in the list here . The string class allows you to create strings from arbitrary data, which can include embedded NULs, as in this case. The initialization list knows its own length, so string captures all characters.

For s1 the matching constructor is (5) in the above list, which takes const char* - the compiler allows the char array to provide decay to such a pointer before calling this constructor, which means that the constructor does not know the length of the array. Instead, it is assumed that you intentionally use the ASCIIZ NUL-terminated convention (as in the "C" lines) and scan the data to find the first NUL, given that the terminator is. Therefore, the line contains only 2 characters.

Please note that you can explicitly write 4 characters with ...

 std::string s1 { "ab\0c", 4}; 

... that matches the constructor (4) in the list.

The Rakete1111 comment below illustrates another, newer way of creating such strings: auto s1 = "ab\0c"s; .

+8
source

The reason is that std :: string are not first class objects, they are standard library objects and must obey C ++ syntax rules. Unlike string literals, which are first-class constructs.

An std :: string is allowed by the built-in nuls, so when it is initialized with an array, it sees the whole array. When it is initialized with a string literal, it sees char *, and its only way to detect the end of a string is to search for null.

0
source

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


All Articles