Lifetime elapsed through the link function
I can do something like this:
const int &i = 5;
and have a temporary lifetime extended to a lifetime i
.
But what about
const int &fun (const int &i){
return i;
}
int main () {
const int &r = fun(5);
// Can I use r here?
}
Has the proxy 5 lifetime extended? Or a r
link to a dangling link?
source to share
This is a chatty link. From the [class.temporary] / 4-5 section:
There are two contexts in which temporary objects are destroyed at a different point than the end of the fullexpression. The first context is when the default constructor is called [...]
The second context is when the binding is tied to a temporary. A temporary that is referenced by a linked or a temporary that is the complete object of the sub-object to which the link is anchored is retained for the lifetime of the link, except:
- Temporal binding to reference element in constructors ctor-initializer [...]
- The timing of the reference parameter in the function call (5.2.2) is retained until completion of the complete expression containing the call .
- [...]
5
persists until the complete expression containing the call completes, namely:
const int &r = fun(5);
// <== no more 5
source to share
No, I do not believe. You have bound 5
to a link that argument fun
, so it lasts as long as that argument continues. The argument is only retained for the duration of the call fun
.
The corresponding standard text was discussed in the previous question .
source to share