Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Is there any difference between

std::string s1("foo"); 

and

std::string s2 = "foo"; 

?

like image 511
cairol Avatar asked Feb 03 '10 13:02

cairol


1 Answers

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.

like image 74
Khaled Alshaya Avatar answered Oct 20 '22 23:10

Khaled Alshaya