问题描述
将对象的返回值存储在引用中是否有效?
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++ 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)