虚析构函数

版权声明:如需转载,请注明出处。 https://blog.csdn.net/Young__Fan/article/details/79970596
#include<iostream>
using namespace std;

class A
{
public:
    A()
    {
         cout << "A()..." << endl;
         this->p = new char[64];
         memset(this->p,0,64);//清空数组
         strcpy(this->p,"A String...");
    }

    virtual void print()
    {
        cout << "A:" << this->p << endl;
    }

    virtual ~A() {//虚析构函数
        cout << "~A()..." << endl;
        if (this->p != NULL) {
            delete[] this->p;
            this->p = NULL;
        }
    }
private:
    char *p;
};

class B :public A
{
public:
    B()
    {//此刻一定会触发A的无参构造
         cout << "B()..." << endl;
         this->p = new char[64];
         memset(this->p,0,64);//清空数组
         strcpy(this->p,"B String...");
    }

    virtual void print()
    {
        cout << "B:" << this->p << endl;
    }

    virtual ~B()
    {
        cout << "~B()..." << endl;
        if (this->p != NULL) {
            delete[] this->p;
            this->p = NULL;
        }
    }

private:
    char *p;
};

void func(A *ap)
{
    ap->print();//在此发生多态

    delete ap;//要使此刻ap-> ~B(),~B()再自动触发~A()
            //即让此刻产生多态,要使用虚析构函数,
            //不然系统默认触发~A(),不再触发~B(),会发生内存泄漏
}

void test()
{
    A *ap = new A;
    func(ap);
    cout << "-------------"<< endl;

    B *bp = new B;
    func(bp);
}
int main()
{
    test();   
    return 0;
}

总结:

void func(A *ap)
  {
    ap->print();//在此发生多态

    delete ap;//要使此刻ap-> ~B(),~B()再自动触发~A()
        //即让此刻产生多态,要使用虚析构函数,
        //不然系统默认触发~A(),不再触发~B(),会发生内存泄漏
阅读更多

扫码向博主提问

Young__Fan

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • C++
  • OpenCV
  • Qt
  • SeetaFace
去开通我的Chat快问
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页