Suppose we have the following piece of C++ code:
struct A
{
int* a;
A()
{
a = new int(5);
}
~A()
{
delete a;
}
};
struct B
{
A a;
int b;
B()
{
a = A();
b = 10;
}
};
int main()
{
B b;
return 0;
}
When running it, A's destructor gets called twice, but why? From what I understand B's implicit destructor calls all the destructors of B's members, which is fine, but when does the second call to A's destructor happen and why? What's the proper way of handling memory in such cases?