struct Foo {
int a_;
Foo(): a_(0) { cout << "Default Ctor : " << a_ << endl; }
Foo(int a): a_(a) { cout << "Ctor with parameters : " << a_ << endl; }
Foo(const Foo& foo): a_(foo.a_) { cout << "Copy Ctor : " << a_ << endl; }
~Foo() { cout << "Dtor : " << a_ << endl; }
};
Foo min(Foo f1, Foo f2) {
return f1.a_ < f2.a_ ? f1 : f2;
}
int main(){
Foo f1(1), f2(2), f3;
f3 = min(f1, f2);
return 0;
}
// Output :
// Ctor with parameters : 1
// Ctor with parameters : 2
// Default Ctor : 0
// Copy Ctor : 1
// Copy Ctor : 2
// Copy Ctor : 1
// Dtor : 1 <- confused about the order here, wondering why the order is not 2 -> 1 -> 1
// Dtor : 2
// Dtor : 1
// Dtor : 1
// Dtor : 2
// Dtor : 1
I am confused about why the return object from the min function is destructed before two local Foo objects. If the return object is destructed even before the min function ends, how can f3 be assigned?