views:

123

answers:

4

It might be a silly question but is there any difference between

std::string s1("foo");

and

std::string s2 = "foo";

?

+3  A: 

there's no difference

eduffy
+9  A: 

Yes and No.

The first is initialized explicitly, and the second is copy initialized. The standards permits to replace the second with the first. In practice, the produced code is the same.

Here is what happens in a nutshell:

std::string s1("foo");

The string constructor of the form:

string ( const char * s );

is called for s1.

In the second case. A temporary is created, and the mentioned earler constructor is called for that temporary. Then, the copy constructor is invoked. e.g:

string s1 = string("foo");

In practice, the second form is optimized, to be of the form of the first. I haven't seen a compiler that doesn't optimize the second case.

AraK
A: 

The first one is better.

The second one will create the instance and will assign the default value (""). Then there will be a secodn assignement : "foo". So 2 assignments instead of 1...

Oodini
No, the second one does not call the assignment operator.
Steve Jessop
+7  A: 

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.

Steve Jessop
You got my +1 for "the standard explicitly permits something called "copy elision" ;)
AraK
Minor confession: after posting I noticed it's "copy constructor elision" in the index, but as far as I remember I've referred to it as "copy elision" :-)
Steve Jessop