Reputation: 1101
Suppose that a function has the signature
std::string GetString();
and that it returns a new string by value. Now given the following code:
// (a) Store the return value to a const reference.
const std::string& my_string = GetString();
// (b) Store the return value to a (const) value.
const std::string my_string = GetString();
Am I correct to understand that (a) and (b) are, from a C++11 compiler's point of view, identical? If so, is there a rough consensus on the choice of style?
Upvotes: 2
Views: 846
Reputation: 141554
Theoretically they are different, but practically they are identical. The only code you can write to tell the difference would involve decltype(my_string)
.
The compiler could generate the same assembly for both.
Upvotes: 0
Reputation: 206567
Am I correct to understand that (a) and (b) are, from a C++11 compiler's point of view, identical?
No, they are not identical.
(a) extends the life of the temporary object returned by GetString()
.
(b) makes a new object. It is constructed by:
std::string
by using the return value of GetString()
as the argument,GetString()
by RTO, orGetString()
.Upvotes: 1