Home > Net >  Lifetime of a reference that has been returned from a function
Lifetime of a reference that has been returned from a function

Time:10-15

For a function T& f() {...} what will be the lifetime of the reference entity created in T x = f(); ?

According to the standard "The lifetime of a reference begins when its initialization is complete and ends as if it were a scalar object.", and while there is a section concerning temporary objects, a reference is not an object so it doesn't seem to apply.

Does this mean that according to the standard, in the example above the reference must actually exist throughout the whole scope block in which T x = f(); lies? That would seem redundant. I can't see any issue if the reference here were treated similarly to how "temporary" objects are - it seems safe for it to stop existing at the end of the full expression in which it is contained.

CodePudding user response:

Does this mean that according to the standard, in the example above the reference must actually exist throughout the whole scope block in which T x = f(); lies?

Yes, the type of the expression f() is actually T and not T&(because in C the type an expression is never a reference type), so you're not actually creating a reference variable x but a normal non-reference variable x. And so the normal scoping rules apply.

Basically, x is being initialized with the value referred to by the reference. From expression's documentation

Each expression has some non-reference type, and each expression belongs to exactly one of the three primary value categories: prvalue, xvalue, and lvalue.

For example,

int& f()
{
    static int i = 0; 
    return i;
}
int main()
{
    {
        int x = f(); //x is a copy of i
        //you can use x here in this block 
    }//scope of x ends 
    
    //can't use x here
}
  • Related