Search code examples
c++const-reference

Storing return value as a const reference versus as a value


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?


Solution

  • 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:

    1. invoking the copy constructor of std::string by using the return value of GetString() as the argument,
    2. being assigned the return value of GetString() by RTO, or
    3. invoking the move constructor using the return value of GetString().