I can do something like this:
const int &i = 5;
and have the lifetime of the temporary extended to the lifetime of i
.
But how about
const int &fun (const int &i){
return i;
}
int main () {
const int &r = fun(5);
// Can I use r here?
}
Is the lifetime of the proxy-5 still extended? Or is r
a dangling reference?
It's a dangling reference. From [class.temporary]/4-5:
There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when a default constructor is called [ ... ]
The second context is when a reference is bound to a temporary. 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 member in a constructor’s ctor-initializer [ ...]
- 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 5
persists until the completion of the full-expression containing the call, which is to say:
const int &r = fun(5);
// <== no more 5
No, I don't believe so. You bound 5
to the reference that's the argument to fun
, so it lasts for as long as that argument lasts. The argument only lasts for the duration of the call to fun
.
The relevant standard text was explored in this previous question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With