Search code examples
c++initializationvariable-assignmentcopy-constructorassignment-operator

Is there a difference between `string s("hello");` and `string s = "hello";`


The title says it all. However, please take string as a placeholder for any class.

std::string s1("hello");  // construct from arguments
std::string s2 = "hello"; // ???
std::string s3;           // construct with default values
s3 = "hello";             // assign

I wonder if the statement for s2 does the same as for s1 or for s3.


Solution

  • The case of s2 is copy initialization. It's initialization, not assignment as case of s3.

    Note that for std::string, the effect is the same for s1 and s2, the apporiate constructor (i.e. std::string::string(const char*)) will be invoked to construct the object. But there's a different between copy intialization and direct initialization (the case of s1); for copy intialization, explicit constructor won't be considered. Assume that std::string::string(const char*) is declared explicit, that means the implicit conversion from const char* to std::string is not allowed; then the 2nd case won't compile again.

    Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.