I was testing out the following code and what confused me is that there is more destructor calls than constructor calls:
#include <iostream>
struct A {
A() { std::cout << 1; }
A(int) { std::cout << 7; }
~A() { std::cout << 5; }
};
struct B {
B() { std::cout << 2; }
B(int) { std::cout << 9; }
~B() {std::cout << 3;}
};
struct C {
B b;
A a1;
A a2;
C() : a1(3){
b = 3;
a2 = 7;
}
};
int main(){
C c;
return 0;
}
The output is like follows:
B() A(int) A() B(int) ~B() A(int) ~A() ~A() ~A() ~B()
2 7 1 9 3 7 5 5 5 3
My guess is that on the lines b = 3 and a2 = 7, 3 and 7 must be implicitly converted to B and A and when they get copied into b and a2, they get destroyed.
Is this correct or is something else going on here?