'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:[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.
- A temporary object of type
std::stringis created using"Eugene"on the right hand side. Then, the copy/move constructor ofstd::stringis used to construct the object namedname. - In C++11, there is non-mandatory copy elision 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 constructnamefrom"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.
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
nameis 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ShadowRanger |
