Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

c++ - Will a reference bound to a function parameter prolong the lifetime of that temporary?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...