Consider the following code:
#include <iostream>
struct A
{
A(){ };
~A(){ std::cout << "~A::A()" << std::endl; };
};
struct B: A { };
B *b = new B; //Doesn't produce any side-effect.
int main(){ }
The program doesn't produce any output which means the destructor isn't being called. But if we replace the destructor's body with the delete
specifier, the program won't even compile.
#include <iostream>
struct A
{
A(){ };
~A() = delete; //{ std::cout << "~A::A()" << std::endl; };
};
struct B: A { };
B *b = new B; //Error: use of deleted function
int main(){ }
due to call to the deleted function. That's the destructor that is being called in that case. Why is there such a difference?
It won't work even if we define B
's constructor explicitly:
#include <iostream>
struct A
{
A(){ };
~A() = delete; //{ std::cout << "~A::A()" << std::endl; };
};
struct B: A
{
B(){ };
};
B *b = new B;
int main(){ }