If there is a difference between two constructs

If there is a difference between two constructs I would like to know

std::string name = std::string("Eugene");

and

std::string name = "Eugene";

Solution 1:

C++11

First lets consider the statement:

std::string name = std::string("Eugene");

For the above shown statement there are 2 possibilities in C++11.

  1. A temporary object of type 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.
  2. In C++11, there is non-mandatory copy elison which means that implementations are allowed to elide the temporary on the right hand side. This means instead of creating a temporary on the right hand side and then using a copy/move constructor to construct 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 eluded.

C++17

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 suitable std::string's constructor.

So the answer to your question in C++17 is that there is no difference between the two statements.