Search code examples
c++explicit-destructor-call

Class and member destructors called twice


class A
{
public:
    ~A()
    {
        std::cout << "A destroyed" << std::endl;
    }
};

class B
{
public:
    A a;
    ~B()
    {
        std::cout << "B destroyed" << std::endl;
    }
};

int main()
{
    B b;
    b.~B();
}

Output:

B destroyed
A destroyed
B destroyed
A destroyed

Can someone explain to me what's going on here? I expected the output to be

B destroyed
A destroyed

(once when ~B() is called and once ~A() is called).


Solution

  • Any object that was created in a limited scope would be destroyed when the scope is exited. Meaning, that if you have created an object on the stack, it will be destroyed when the stack will fold back, along with any other variables declared in that scope.

    The only exception to this is when you are using dynamic allocation of objects, using the keyword new, this creates the object on the heap, which doesn't clean itself on its own. But even then, calling delete will invoke the destructor on its own.

    Having said that, in order to avoid using new and delete, and for better resource management, there are types (such as smart-pointers) that handle these on their own, in a technique called Resource Allocation Is Initialization (or RAII), which makes things much simpler (and you get to the first part, all is allocated on the stack, thus the destructors are being called automatically when it folds).