Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime of temporary passed through function by reference [duplicate]

Tags:

c++

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?

like image 746
Baum mit Augen Avatar asked May 29 '15 00:05

Baum mit Augen


2 Answers

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
like image 193
Barry Avatar answered Sep 28 '22 05:09

Barry


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.

like image 44
Lightness Races in Orbit Avatar answered Sep 28 '22 07:09

Lightness Races in Orbit