C++ 析构函数的调用顺序
如果指针指向基类,但是指针在运行时指向派生类,则该基类必须具有虚拟析构函数,以便破坏派生类。如果没有虚拟析构函数,则只会运行基类的析构函数。
比如:
Base* basePtr; basePtr = new Derived(1);
如果没有添加virtual,也就是没有虚拟析构函数,看下面代码示例:
#include <iostream> using namespace std; class Base { public: Base() { cout << "Base contruction" << endl; } ~Base() { cout << "Base deconstruction" << endl; } }; class Derived : public Base { public: Derived() { cout << "Derived contruction " << endl; } ~Derived() { cout << "Derived deconstruction" << endl; } }; int main() { Base* basePtr; Derived* derevedPtr; basePtr = new Derived; delete basePtr; }
则只会调用基类的析构函数
结果:
Base contruction
Derived contruction
Base deconstruction
在添加virtual之后,就会先用派生类的析构函数,再调用基类的析构函数
这样添加:
virtual ~Base()
结果:
Base contruction
Derived contruction
Derived deconstruction
Base deconstruction
最后再提一下,如果指针是派生类声明的,并且是指向派生类的,那么调用顺序是基类构造->派生类构造->派生类析构->基类析构
如果指针是基类声明,并且指向基类的,那么调用顺序是基类构造->基类析构
一些有用的blog: Understanding warning C4265: class has virtual functions