Jae Heon Lee
Jae Heon Lee

Reputation: 1101

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?

Upvotes: 2

Views: 846

Answers (2)

M.M
M.M

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

R Sahu
R Sahu

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:

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

Upvotes: 1

Related Questions