3
class obj {
};

obj func() {
    return obj();
}

int main() {
   obj& o = func(); // possible?
}

What is the scope the return value of a function that returns objects by value? in other word, inside the scope that this function is called, is it possible to take the reference of the returned by value object?

Tal Avissar
  • 10,088
  • 6
  • 45
  • 70
mkmostafa
  • 3,071
  • 2
  • 18
  • 47
  • 2
    const obj& o = func(); // possible – AnatolyS May 06 '16 at 08:32
  • So taking the reference is valid. Is the const revelant? – mkmostafa May 06 '16 at 08:33
  • 1
    Possible duplicate of [How come a non-const reference cannot bind to a temporary object?](http://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object) – LogicStuff May 06 '16 at 08:35
  • [*GotW #88: A Candidate For the “Most Important `const`”*](https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/) – BoBTFish May 06 '16 at 08:36

3 Answers3

2

You cannot take non-const reference of temporary.

You may do

  • obj o = func(); // new obj created but copy constructor may be ellided
  • const obj& o = func(); // lifetime extended
  • obj&& o = func(); // lifetime extended
Jarod42
  • 203,559
  • 14
  • 181
  • 302
2

Yes, you can bind a reference to the return value of a function. This extends the lifetime of the returned object to that of the reference (if it's global or function-local), or to the end of the current function (if the reference is a data member).

However, you cannot bind a temporary (prvalue) to a non-const lvalue reference. So it's like this:

obj& o = func(); // illegal, because non-const lvalue ref
const obj& o = func(); // fine, lifetime extended
obj&& o = func(); // fine, lifetime extended
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

It's not allowed by the language to take a non-const reference of temporary, you can however:

const obj& o = func();
// or
obj&& o = func();
// or simply
obj o = func();
Andreas DM
  • 10,685
  • 6
  • 35
  • 62