I answered it here
One thing I introduced into this answer here: No assignment operator uses.
A brief explanation for a specific line. std::string has a constructor that takes one argument, which takes char const* :
Now you see that the constructor has a pointer to the character (s). So that he can take a string literal. I think the following case is obvious:
string s("hello");
It will invoke the constructor directly and initialize s thereby. This is called direct initialization.
Another way to initialize a variable is called copy initialization. The standard says for the case of copy initialization, when the initializer does not have the type of the object being initialized, the initializer is converted to the corresponding type.
// uses copy initialization string s = "hello";
Specify Types First
s is of type std :: string"hello" is an array, which in this case is again treated as a pointer. Therefore, we will consider it as char const* .
The compiler is looking for two ways to do the conversion.
- Is there a conversion constructor to std :: string?
- Does the initializer have a type that has a conversion operator function that returns
std::string ?
It will create a temporary std::string one of these ways, which will then be used to initialize the s object using the std::string copy constructor. And he sees that std::string has a conversion constructor that the initializer accepts. So it uses. In the end, itβs actually the same as
std::string s(std::string("hello"));
Note that the form that is used in your example that caused all this
std::string s = "hello";
defines an implicit conversion. You can mark the constructor by specifying char const* as explicit for your types if you are wondering about the initialization rules for your material, and it will no longer be able to use the corresponding constructor as the conversion constructor:
class string { public: explicit string(char const* str) {
At the same time, initialization using copy initialization and a char const* actually prohibited (and in other places)!
Now, if the compiler does not support the allocation of temporary files in different places. The compiler is allowed to assume that the copy instance is copying in this context and can exclude an additional copy of the temporary string and instead create a temporary std :: string directly into the initialized object. However, the copy constructor must be available in particular. So copy initialization is invalid if you do this
class string { public: explicit string(char const* str) {
Now, in fact, only the case with direct initialization is valid.