3

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()
2
  • 2
    D should delete q in its destructor. Forbid copy construction. Commented May 1, 2016 at 19:39
  • "even after using unique_ptr" - your code doesn't use unique_ptr Commented May 1, 2016 at 21:13

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And do not forget about the rule of three
That's great . Thank you everyone .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.