Reputation: 21
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.
Upvotes: 0
Views: 85
Reputation: 29942
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:
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.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.
Upvotes: 4
Reputation: 13134
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.
Upvotes: 3
Reputation: 122133
"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
.
Upvotes: 1