Store return value of function in reference C++

后端 未结 3 477
星月不相逢
星月不相逢 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 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();
    

提交回复
热议问题