Store return value of function in reference C++

后端 未结 3 471
星月不相逢
星月不相逢 2020-12-12 18:01

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

class A { ... };
A myFunction()
{
    A myObject;
    return myObject;
} //myObject goes o         


        
相关标签:
3条回答
  • 2020-12-12 18:41

    You might be interested in the return-by-value optimization that many compilers make to avoid calling the copy constructor.

    0 讨论(0)
  • 2020-12-12 18:56

    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.

    0 讨论(0)
  • 2020-12-12 19:06

    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();
    
    0 讨论(0)
提交回复
热议问题