什么是C++虚析构函数?什么时候使用?

Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor.

什么时候使用?
当你通过指针删除一个基类的派生类的实例的时候

Constructing base
Constructing derived
Destructing base

#include

using namespace std;
class Base
{
public:
    Base() {
        cout << "Base class constructor" << endl;
    }
    ~Base() {
        cout << "Base class destructor" << endl;
    }

private:


};

class Derival:public Base
{
public:
    Derival() {
        cout << "Constructing derived " << endl;
    }
    ~Derival() {
        cout << "Destructing derived" << endl;
    }

private:

};

int main() {
    Derival *d = new Derival();
    Base *b = d;
    //Base *b = new Derival();
    delete b;
    system("pause");
    return 0;

}
output

可以看到派生类的析构函数并没有执行

/*!
 * \file vitualdestructor.cpp
 * \date 2017/02/24 13:13
 *
 * \author henry
 * Contact: [email protected]
 *
 * \brief 
 *
 * TODO: long description
 *
 * \note
*/
#include
using namespace std;
class Base
{
public:
    Base() {
        cout << "Base class constructor" << endl;
    }
    virtual ~Base() {
        cout << "Base class destructor" << endl;
    }

private:


};

class Derival:public Base
{
public:
    Derival() {
        cout << "Constructing derived " << endl;
    }
    ~Derival() {
        cout << "Destructing derived" << endl;
    }

private:

};

int main() {
    Derival *d = new Derival();
    Base *b = d;
    //Base *b = new Derival();
    delete b;
    system("pause");
    return 0;
}

output--virtual

[In delete b], if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

你可能感兴趣的:(什么是C++虚析构函数?什么时候使用?)