我有这个代码(简体版):
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.
编辑:“参考文献的临时性”在参考的一生中仍然存在“.在这种情况下,引用的生存期在赋值表达式的末尾结束,临时整数的生命周期也一样.