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?
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()
.