user3798283
user3798283

Reputation: 467

How to delete an object in C++?

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()

Upvotes: 3

Views: 78

Answers (1)

tobspr
tobspr

Reputation: 8376

You are never freeing the pointers passed to your objects, so their destructors will never be called.

You need to delete the pointers in your destructor, to make sure the destructor of the stored object is called too:

class D: public P
{
    P *q;
public:
    D(P *p) : q(p) { cout << "D()" << endl; }
    ~D() { delete q; cout << "~D()" << endl; }
};

You also have to modify your copy constructor then (see Rule of Three). This is problematic in this case, since you would either have to copy the pointers value, or let both instances point to the same object. In the latter case, you would have to take care about not deleting the pointer twice.

However, this is where C++ smart pointers were made for. A much simpler way would be:

class D : public P
{
    unique_ptr<P> q;
public:
    D(P *p) : q(p) {} 
};

This way you don't have to keep track of the pointer, and you also don't have to override any copy constructors and such.

Upvotes: 5

Related Questions