Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 383
Fabian Avatar asked May 18 '26 09:05

Fabian


2 Answers

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.

like image 77
songyuanyao Avatar answered May 21 '26 00:05

songyuanyao


In this case, s1 and s2 do exactly the same thing: they both call the constructor to const char*. (Some folk prefer to use = for clarity).

For s3, the default constructor is called, followed by operator= to const char*.

like image 39
Bathsheba Avatar answered May 20 '26 23:05

Bathsheba