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

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

概述我有这个代码(简体版): 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 我有这个代码(简体版):
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.

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

总结

以上是内存溢出为你收集整理的c – 参考绑定到一个函数参数可以延长该临时的生命周期吗?全部内容,希望文章能够帮你解决c – 参考绑定到一个函数参数可以延长该临时的生命周期吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1253672.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存