c++object-lifetime

Does lifetime extension also construct an object on the stack?


Given a function returning an object of class type T

T GetT()
{
   T t;
   ...
   return t;
}

To me, the only difference between lifetime extension

const T& t1 = GetT();

and normal construct

T t2 = GetT(); // copy elision

is that t1 is a const reference, while t2 is a normal lvalue. They have the same behavior other than types.

Does lifetime extension do anything different from simply creating an object on the stack but limit its access as const?

Does lifetime extension do more magic to reduce the cost of constructing a normal object?


Solution

  • Does lifetime extension do anything different from simply creating an object on the stack but limit its access as const?

    No, it doesn't do more than binding to the object returned from the function, and yes that object has automatic storage duration. But lifetime extension doesn't have to make things const. A rvalue reference can do lifetime extension as well, without needing to make things const.

    T&& t3 = GeT();
    

    Does lifetime extension do more magic to reduce the cost of constructing a normal object?

    No, the object is always going to need to be initialized and destroyed in the scope where GetT() appears. All the reference does is make those two events in the code be further apart. A local variable will behave the same.

    Where references behave differently, is if you have inheritance thrown into the mix, along with overload resolution.

    class Base{};
    class D1 : public Base{};
    class D2 : public Base{};
    
    D1 get(int);
    D2 get(char);
    
    int main() {
      Base&& b1 = get(0);
      Base&& b2 = get('0');
    }
    

    In that example, b1 and b2 bind to objects of different types (and the compiler keeps track of the type, without slicing). That may not seem like a very useful feature in a world where auto&& exists, but it had its uses pre-c++11.