加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 参考绑定到一个函数参数可以延长该临时的生命周期吗?

发布时间:2020-12-16 03:11:37 所属栏目:百科 来源:网络整理
导读:我有这个代码(简体版): const int function( const int param ){ return param;}const int reference = function( 10 );//use reference 我不能很明确地决定C 03标准$12.2 / 5的措辞 The temporary to which the reference is bound or the temporary that
我有这个代码(简体版):
const int& function( const int& param )
{
     return param;
}

const int& reference = function( 10 );
//use reference

我不能很明确地决定C 03标准$12.2 / 5的措辞

The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference…

适用于此.

上述代码中的引用变量有效还是悬挂?调用代码中的引用是否会将临时传递的生存期延长为参数?

解决方法

全表达式是不是另一个表达式的子表达式的表达式.在这种情况下,包含调用函数(10)的全表达式是赋值表达式:
const int& reference = function( 10 );

为了使用参数10调用函数,将为临时整数对象10创建一个临时const引用对象.临时整数和临时const引用的生命周期通过赋值进行扩展,因此尽管赋值表达式有效,尝试使用引用引用的整数是Undefined Behavior作为引用不再引用活动对象.

我认为C11标准澄清了以下情况:

The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:

— A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.

编辑:“参考文献的临时性”在参考的一生中仍然存在“.在这种情况下,引用的生存期在赋值表达式的末尾结束,临时整数的生命周期也一样.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读