将对象的返回值存储在引用中是否有效?
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();
}
是否可以这样做以避免将 myObject 复制到 mySecondObject?不再需要 myObject 并且应该与 mySecondObject 完全相同,因此理论上将对象的所有权从一个对象传递给另一个对象会更快.(这也可以使用 boost 共享指针,但它具有共享指针的开销.)
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.)
提前致谢.
不允许将临时引用绑定到非常量引用,但是如果您使引用为常量,则会将临时引用的生命周期延长到引用,见 这篇 Danny Kalev 关于它的帖子.
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.
简而言之:
const A& mySecondObject = myFunction();
这篇关于将函数的返回值存储在参考 C++ 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!