cairol
cairol

Reputation: 8773

What are the differences in string initialization in C++?

Is there any difference between

std::string s1("foo");

and

std::string s2 = "foo";

?

Upvotes: 22

Views: 17831

Answers (4)

Steve Jessop
Steve Jessop

Reputation: 279225

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.

Upvotes: 13

Khaled Alshaya
Khaled Alshaya

Reputation: 96849

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.

Upvotes: 27

Oodini
Oodini

Reputation: 1112

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...

Upvotes: -5

eduffy
eduffy

Reputation: 40224

there's no difference

Upvotes: 3

Related Questions