Store return value of function in reference C++

Ruud picture Ruud · May 12, 2010 · Viewed 15.6k times · Source

Is it valid to store the return value of an object in a reference?

class A { ... };
A myFunction()
{
    A myObject;
    return myObject;
} //myObject goes out of scope here

void mySecondFunction()
{
    A& mySecondObject = myFunction();
}

Is it possible to do this in order to avoid copying myObject to mySecondObject? myObject is not needed anymore and should be exactly the same as mySecondObject so it would in theory be faster just to pass ownership of the object from one object to another. (This is also possible using boost shared pointer but that has the overhead of the shared pointer.)

Thanks in advance.

Answer

Alexander Torstling picture Alexander Torstling · May 12, 2010

It is not allowed to bind the temporary to a non-const reference, but if you make your reference const you will extend the lifetime of the temporary to the reference, see this Danny Kalev post about it.

In short:

const A& mySecondObject = myFunction();