Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store return value of function in reference C++

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.

like image 870
Ruud Avatar asked May 12 '10 19:05

Ruud


2 Answers

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(); 
like image 111
Alexander Torstling Avatar answered Sep 24 '22 13:09

Alexander Torstling


It's possible with a const reference.

myFunction returns by value, so that return value is a temporary object. You can bind a temporary to a const reference, and the lifetime of the temporary is extended to the lifetime of the reference. You can't bind a temporary to a non-const reference (unfortunately).

The return value of myFunction might be a copy of myObject. On the plus side, copy constructor elision (aka the "named return value optimisation" in this case) permits the compiler to construct myObject directly into the temporary which is the return value of myFunction, presumably located somewhere on the stack of the calling code. If it does that, then when myObject goes out of scope the object is not actually destroyed. The optimisation is commonly implemented - for example GCC (usually?) does it even without any optimisation flags.

Copy ctor elision also permits the compiler to avoid all copying if you did:

A mySecondObject = myFunction(); 

This requires the application of both legal types of copy ctor elision: (1) returning a named value from a function, and (2) initializing an object from a temporary.

like image 25
Steve Jessop Avatar answered Sep 24 '22 13:09

Steve Jessop