Search code examples
c++lifetimetemporary

const class can extend lifetime of const member ref of temporary?


struct  A {

// something

~A() { std::cout <<  "A destruct!\n"; }

};

class  refWrapper {

public:

refWrapper(const  A&  a) : a_(a) {}

~refWrapper() { std::cout <<  "refWrapper destruct!\n"; }

private:

const A& a_;

};

void  func(const  refWrapper&  ref  =  A()) {

// why ~A after ~refWrapper

// Rather than after refWrapper constructor complete

}

Solution

  • With default arguments, the call

    func();
    

    is equivalent to

    func(A()); // so func(refWrapper(A()));
    

    So,

    • temporary A is created first (destroyed at end of full expression)
    • temporary refWrapper is created second (bound to parameter reference)
    • temporary refWrapper destroyed.
    • temporary A destroyed.

    Notice that there is an exception for lifetime extension or parameter:

    A temporary object bound to a reference parameter in a function call ([expr.call]) persists until the completion of the full-expression containing the call.

    So refWrapper is destroyed at end of full expression, and not at the end of func call (which is the same moment in given example though). So destruction should be done in reverse order of construction.