Reputation: 11
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
}
Upvotes: 0
Views: 84
Reputation: 217135
With default arguments, the call
func();
is equivalent to
func(A()); // so func(refWrapper(A()));
So,
A
is created first (destroyed at end of full expression)refWrapper
is created second (bound to parameter reference)refWrapper
destroyed.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.
Upvotes: 1