The constructor and destructor calls are not matching , even after using unique_ptr . Is there any way to make the constructor and destructor call to match otherwise there will be memory leak .
#include <iostream>
using namespace std;
class P
{
public:
P() { cout<<"P()\n"; }
virtual ~P() { cout<<"~P()\n"; }
};
class D: public P
{
P *q;
public:
D(P *p):q(p) { cout<<"D()\n"; }
~D() { cout<<"~D()\n"; }
};
class A: public D
{
public:
A(P *p):D(p) { cout<<"A()\n"; }
~A() { cout<<"~A()\n"; }
};
class B: public D
{
public:
B(P *p):D(p) { cout<<"B()\n"; }
~B() { cout<<"~B()\n"; }
};
int main()
{
P *p = new B(new A(new P()));
delete p;
return 0;
}
OUTPUT:
P()
P()
D()
A()
P()
D()
B()
~B()
~D()
~P()
Dshoulddelete qin its destructor. Forbid copy construction.