Reputation: 25
If there is a difference between two constructs I would like to know
std::string name = std::string("Eugene");
and
std::string name = "Eugene";
Upvotes: 0
Views: 101
Reputation: 1
First lets consider the statement:
std::string name = std::string("Eugene");
For the above shown statement there are 2 possibilities in C++11.
std::string
is created using "Eugene"
on the right hand side. Then, the copy/move constructor of std::string
is used to construct the object named name
.name
, implementations can just directly construct name
from "Eugene"
.Now lets consider the statement:
std::string name = "Eugene"; //this is initialization
In the above statement, an object named name
is constructed using the string literal and a suitable std::string
's constructor.
So, the answer to your question in C++11 is that there is a difference between the two statements only if the temporary is not elided.
In C++17, there is mandatory copy elison which means that in this case when we write:
std::string name = std::string("Eugene");
In the above statement, the language guarantees that
No temporary on the right hand side is created. Instead, the object
name
is created directly using the string literal"Eugene"
and a suitablestd::string
's constructor.
So the answer to your question in C++17 is that there is no difference between the two statements.
Upvotes: 2