Is there any difference between
std::string s1(\"foo\");
and
std::string s2 = \"foo\";
?
On the face of it, the first one calls the const char*
constructor to initialize s1
. The second one uses the const char*
constructor to initialize a temporary value, and then uses the copy constructor, passing in a reference to that temporary value, to initialize s2
.
However, the standard explicitly permits something called "copy elision", which means that as AraK says, the second can legally be replaced with the first even if the copy constructor has observable side-effects, so that the change affects the output of the program.
However, when this replacement is done, the compiler must still check that the class has an accessible copy constructor. So a potential difference is that the second form requires a copy constructor to be callable, even though the compiler doesn't have to call it. Obviously std::string
does have one, so in this case that doesn't make a difference, but for other classes it could.