将函数的返回值存储在引用C ++中 [英] Store return value of function in reference C++

查看:110
本文介绍了将函数的返回值存储在引用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();
}

是否可以执行此操作以避免将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.)

提前感谢。

推荐答案

不允许将临时绑定到非const引用,但是如果你引用const,你会将临时的生命周期延长到引用, a href =http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=199>这个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 ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆