const引用是否可以延长由临时对象返回的临时对象的寿命? [英] Does const reference prolong the life of a temporary object returned by a temporary object?

查看:95
本文介绍了const引用是否可以延长由临时对象返回的临时对象的寿命?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道const引用可以延长本地临时目录的寿命.现在,我问自己是否可以在一系列临时对象上扩展这种专有性,即是否可以安全地定义:

I know that const reference prolongs the life of a temporary locally. Now I am asking myself if this propriety can be extended on a chain of temporary objects, that is, if I can safely define:

std::string const& foo = aBar.getTemporaryObject1().getTemporaryObject2();

我的感觉是,由于第一个方法aBar.getTemporaryObject1()已经返回了一个临时对象,因此aBar.getTemporaryObject2()的所有权不成立.

My feeling is that, since the the first method aBar.getTemporaryObject1() returns already a temporary object, the propriety doesn't hold for aBar.getTemporaryObject2().

推荐答案

生存期扩展仅在引用直接绑定到该临时目录时适用.

The lifetime extension only applies when a reference is directly bound to that temporary.

例如,从该引用初始化另一个引用不会进行其他扩展.

For example, initializing another reference from that reference does not do another extension.

但是,在您的代码中:

std::string const& foo = aBar.getTemporaryObject1().getTemporaryObject2();

您直接将foo绑定到getTemporaryObject2()的返回值,假设这是一个按值返回的函数.这是另一个临时对象的成员函数还是任何其他函数都没有关系.这样的代码就可以了.

You are directly binding foo to the return value of getTemporaryObject2() , assuming that is a function that returns by value. It doesn't make a difference whether this was a member function of another temporary object or whatever. So this code is OK.

getTemporaryObject1()返回的对象的生存期没有延长,但这并不重要(除非getTemporaryObject2的返回值包含对该对象的引用或指针,或其他东西,但是因为它显然是,但不能).

The lifetime of the object returned by getTemporaryObject1() is not extended but that doesn't matter (unless getTemporaryObject2's return value contains references or pointers to that object, or something, but since it is apparently a std::string, it couldn't).

这篇关于const引用是否可以延长由临时对象返回的临时对象的寿命?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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