Is there any difference between
std::string s1("foo");
and
std::string s2 = "foo";
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With