C/C++ 虚析构函数
虚析构函数是为了解决基类指针指向派生类对象,并用基类指针delete派生类对象,导致的内存泄漏问题。
class Base { public: Base(){ a = 1; } // 1) virtual ~Base() { cout << "destruct base." << endl; } // 2) ~Base() { cout << "destruct base." << endl; } private: int a; }; class Derived : public Base { public: Derived(){ b = 2; } ~Derived() { cout << "destruct derived." << endl; } private: int b; }; Base *bp = new Derived; delete bp; 输出: 1)动态绑定,先调用~Derived(),再调用~Base() destruct derived. destruct base. 2)静态绑定,调用~Base(),int b没释放 destruct base.