简体   繁体   中英

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.

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

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.

您可能对许多编译器为避免调用复制构造函数而进行的按值返回优化感兴趣。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM