为什么我的析构函数从未调用过? [英] Why is my destructor never called?

查看:139
本文介绍了为什么我的析构函数从未调用过?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类A和一个派生类B:

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.

推荐答案

你的基类需要一个虚拟析构函数。否则,如果只使用A *类型的指针,派生类的析构函数将不会被调用。

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.

添加

virtual ~A() {};

到A类。

这篇关于为什么我的析构函数从未调用过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆