Lets say I have two simple classes like this with non-virtual destructors:
struct A
{
~A() { std::cout << "A destructor" << std::endl; }
}
struct B : A
{
~B() { std::cout << "B destructor" << std::endl; }
}
When an instance of B
is destructed, the destructor of A
is called as well. When I destruct an instance of B
through a pointer of type A*
then B
s destructor will not be called. Does this also count for explicitly calling the destructor in a way you would also call a normal member function?
struct A
{
~A() { std::cout << "Hello" << std::endl; }
void f() { std::cout << "Hello" << std::endl; }
}
A a;
a.~A(); // case 1
a.f(); // case 2
In this example, is there any difference between the two cases other than the name of the function that is called?
EDIT: Consider the same example with CRTP:
template <typename C>
struct A
{
~A() { static_cast<C*>(this)->~C(); }
}
struct B : public A<B>
{
~B() { std::cout << "B destructor" << std::endl; }
}
A<B>* a = new B();
delete a;
Would this cause undefined behaviour or a memory leak?