简体   繁体   中英

What is the difference between the following declarations?

string str("Hello World");
string str="Hello World";

I don't seem to understand the difference between the two. According to my textbook, the operation that the first statement performs is "Initialization constructor using C string". So does the first statement define a C string and the second statement define a C++ string? Also please explain the difference between a C string and a C++ string.

Both lines create a C++ std::string named str . And both initialize them from a C string. The difference is, how they are initialized:

The first is direct initialization :

string str("Hello World");

This calls the string(const char *) constructor.

The second is copy initialization :

string str = "Hello World";

This needs that the string(const char *) constructor is non- explicit (for the previous method, the constructor can be explicit ). We have a little bit differing behavior, depending on the version of the standard:

  • pre C++17: first, a temporary object is created (with string(const char *) ), and then the copy (or move) constructor is called to initialize str . So, the copy (or move) constructor needs to be available. The copy constructor phase can be elided (so the object will be created just like as the direct initialization case), but still, the copy (or move) constructor needs to be available. If it is not available, the code will not compile.
  • post C++17: here, because the standard guarantees copy elision , only the string(const char *) constructor is called. Copy (or move) constructor doesn't need to be available. If copy constructor is not available, the code still compiles.

So, for this particular case, there is no real difference in the end between the two initializations, and therefore, both str strings will become the same.

Both lines define a variable of type std::string named str that is constructed by the constructor of std::string that takes a char const* as its argument. There is no difference in those lines.

[...] C string [...] C++ string [...]?

What is commonly called a C-string is nothing but a zero terminated array of char :

"foobar"; // an array of 7 const chars. 7 instead of 6 because it is 0-terminated.
char foo[] = "foobar";  // an array of 7 chars initialized by the string given

std::string however is a class of the C++ standard library that manages string resources of dynamic length.

"Hello World" is the c-string (null terminated sequence of characters). string (or std::string as its complete name is) is a c++ string (not null terminated) in both cases.

Both lines call the same constructor that takes the c string and constructs a std::string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM