Search code examples
c++lifetimervaluetemporary-objectsreference-binding

Does const reference prolong the life of a temporary object returned by a temporary object?


I know that const reference prolongs the life of a temporary locally. Now I am asking myself if this propriety can be extended on a chain of temporary objects, that is, if I can safely define:

std::string const& foo = aBar.getTemporaryObject1().getTemporaryObject2();

My feeling is that, since the the first method aBar.getTemporaryObject1() returns already a temporary object, the propriety doesn't hold for aBar.getTemporaryObject2().


Solution

  • The lifetime extension only applies when a reference is directly bound to that temporary.

    For example, initializing another reference from that reference does not do another extension.

    However, in your code:

    std::string const& foo = aBar.getTemporaryObject1().getTemporaryObject2();
    

    You are directly binding foo to the return value of getTemporaryObject2() , assuming that is a function that returns by value. It doesn't make a difference whether this was a member function of another temporary object or whatever. So this code is OK.

    The lifetime of the object returned by getTemporaryObject1() is not extended but that doesn't matter (unless getTemporaryObject2's return value contains references or pointers to that object, or something, but since it is apparently a std::string, it couldn't).