Why is my destructor never called?

2019-04-04 15:25发布

I have a base class A and a derived class B:

class A
{
public:
    virtual f();
};

class B : public A
{
public:
     B()
     {
         p = new char [100];
     }
     ~B()
     {
         delete [] p;
     }
     f();
private:
    char *p;
};

For any reason the destructor is never called - why? I dont understand this.

4条回答
三岁会撩人
2楼-- · 2019-04-04 15:35

Class A should have a virtual destructor. Without that, derive class destructors won't be called.

查看更多
Animai°情兽
3楼-- · 2019-04-04 15:52

If your variable is of type A it doesn't have a virtual destructor and so it won't look at the actual runtime type of the object to determine it needs to call the desstructor

Add an empty destructor to A

virtual ~A() {}

and that should fix it.

In general you need to do this on any class that can possibly be used as a base class.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-04-04 15:54

try this:

class A
{
public:
    virtual ~A() {}
    virtual f();
};

class B : public A
{
public:
     B()
     {
         p = new char [100];
     }
     virtual ~B() // virtual keywork optional but occasionally helpful for self documentation.
     {
         delete [] p;
     }
     f();
private:
    char *p;
};
查看更多
时光不老,我们不散
5楼-- · 2019-04-04 15:56

Your base class needs a virtual destructor. Otherwise the destructor of the derived class will not be called, if only a pointer of type A* is used.

Add

virtual ~A() {};

to class A.

查看更多
登录 后发表回答