• C++继承中的虚析构函数


    看看下面程序有什么错误:

    #include <iostream>
    using namespace std;

    class Father
    {
    public:
    Father(){};
    ~Father(){};
    };

    class Son:public Father
    {
    public:
    Son(){};
    ~Son(){};
    };

    int main()
    {
    Father *pfather=new Son;
    delete pfather;
    pfather=NULL;

    return 0;
    }

    该程序在VC++6.0运行后并未发生错误,何解?

    修改上面程序如下:

    #include <iostream>
    using namespace std;

    class Father
    {
    public:
    Father(){cout<<"contructor Father!"<<endl;};
    ~Father(){cout<<"destructor Father!"<<endl;};
    };

    class Son:public Father
    {
    public:
    Son(){cout<<"contructor Son!"<<endl;};
    ~Son(){cout<<"destructor Son!"<<endl;};
    };

    int main()
    {
    Father *pfather=new Son;
    delete pfather;
    pfather=NULL;

    return 0;
    }

    运行结果:

    contructor Father!
    contructor Son!
    destructor Father!

           显然派生类Son并没有析构,马上引出了C++继承中的虚析构函数问题。

    (1)基类的的析构函数不是虚函数的话,删除指针时,只有其类的内存被释放,派生类的没有。这样就内存泄漏了。

    (2)析构函数不是虚函数的话,直接按指针类型调用该类型的析构函数代码,因为指针类型是基类,所以直接调用基类析构函数代码。

    (3)问:啥已经delete p了还能给p赋值啊。。。不解,求高人指点??

           答:delete是删除指针p指向的实例,p指针本身依然存在,delete后将p置为空值是常用做法,空值一般写成NULL宏,其实就是0。因为内存0位置是不允许访问的,delete 0操作编译器可以判断是错误操作不会执行,因此将p置为空值0是很安全的做法。

    (4)养成习惯:基类的析构一定virtual。

    (5)当基类指针指向派生类的时候,如果析构函数不声明为虚函数,在析构的时候,不会调用派生类的析构函数,从而导致内存泄露。

    (6)子类对象创建时先调用父类构造函数然后在调用子类构造函数,在清除对象时顺序相反,所以delete p只清除了父类,而子类没有清除。。。

    (7)当基类对象的指针或引用调用派生类对象时,如果基类的析构函数不是虚析构函数,则通过基类指针或引用对派生类的析构是不彻底的。

     

    后语:

    (1) 对于这个程序,实际上是没有关系的,delete pfather虽然只调用了Father类的析构函数,但是程序运行完成,退出main函数后,Son类的部分数据也会被自动清除。
    (2)那么什么时候才要用虚析构函数呢?通常情况下,程序员的经验是,当类中存在虚函数时要把析构函数写成virtual,因为类中存在虚函数,就说明它有想要让基类指针或引用指向派生类对象的情况,此时如果派生类的构造函数中有用new动态产生的内存,那么在其析构函数中务必要delete这个数据,但是一般的像以上这种程序,这种操作只调用了基类的析构函数,而标记成虚析构函数的话,系统会先调用派生类的析构函数,再调用基类本身的析构函数。 
    (3)一般情况下,在类中有指针成员的时候要写copy构造函数,赋值操作符重载和析构函数。 

    修改后程序:

    #include <iostream>
    using namespace std;

    class Father
    {
    public:
    Father(){cout<<"contructor Father!"<<endl;};
    virtual ~Father(){cout<<"destructor Father!"<<endl;};
    };

    class Son:public Father
    {
    public:
    Son(){cout<<"contructor Son!"<<endl;};
    ~Son(){cout<<"destructor Son!"<<endl;};
    };

    int main()
    {
    Father *pfather=new Son;
    delete pfather;
    pfather=NULL;

    return 0;
    }

    运行结果:

    contructor Father!
    contructor Son!
    destructor Son!
    destructor Father!





  • 相关阅读:
    C++ template —— 类型区分(十一)
    C++ template —— 表达式模板(十)
    C++ template —— template metaprogram(九)
    C++ template —— 模板与继承(八)
    [转]2015有得有悟,2016笨鸟起飞
    C++ template —— trait与policy类(七)
    protobuf与json相互转换的方法
    如何通过卡面标识区分SD卡的速度等级
    MyEclipse设置字体和背景的方法
    JAVA中日期转换和日期计算的方法
  • 原文地址:https://www.cnblogs.com/danshui/p/2385235.html
Copyright © 2020-2023  润新知