且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

绑定到函数参数的引用会延长该临时对象的寿命吗?

更新时间:2023-11-11 23:01:28

完整表达式是一个表达式,它不是另一个表达式的子表达式.在这种情况下,包含调用function( 10 )的完整表达式是赋值表达式:

const int& reference = function( 10 );

为了使用参数10调用function,将为临时整数对象10创建一个临时const引用对象.临时整数和临时const引用的生存期会贯穿该赋值,因此,尽管赋值表达式有效,但尝试使用reference所引用的整数是未定义行为,因为reference不再引用活动对象./p>

我认为C ++ 11标准澄清了这种情况:

引用所绑定的临时对象或引用所绑定的子对象的完整对象的临时对象在引用的生存期内一直存在,除了:

...

-函数调用(5.2.2)中与参考参数的临时绑定一直存在,直到包含该调用的完整表达式完成为止.

引用绑定到的临时对象在引用的生存期内一直存在."在这种情况下,引用的生存期将在赋值表达式的末尾结束,临时整数的生存期也将结束.

I have this code (simplified version):

const int& function( const int& param )
{
     return param;
}

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

I can't quite decide to which extent C++03 Standard $12.2/5 wording

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...

is applicable here.

Is reference variable in the code above valid or dangling? Will the reference in the calling code prolong the lifetime of the temporary passed as the parameter?

A full-expression is an expression that is not a subexpression of another expression. In this case, the full-expression containing the call function( 10 ) is the assignment expression:

const int& reference = function( 10 );

In order to call function with the argument 10, a temporary const-reference object is created to the temporary integer object 10. The lifetime of the temporary integer and the temporary const-reference extend through the assignment, so although the assignment expression is valid, attempting to use the integer referenced by reference is Undefined Behavior as reference no longer references a live object.

The C++11 Standard, I think, clarifies the situation:

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.

"The temporary to which the reference is bound ... persists for the lifetime of the reference". In this case, the lifetime of the reference ends at the end of the assignment expression, as does the lifetime of the temporary integer.