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

我有这个代码(简体版):
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++指针和引用的选择最近在看...
关于vtordisp知多少?我相信不少人看到这篇文章,多半是来自...
那些陌生的C++关键字学过程序语言的人相信对关键字并...
命令行下的树形打印最近在处理代码分析问题时,需要将代码的...
虚函数与虚继承寻踪封装、继承、多态是面向对象语言的三大特...