前面我们已经说过, 构造函数不可以为虚函数。 现在, 我们要说, 析构函数可以为虚函数, 而且通常需要为虚函数。 先看一个简单的程序:
- #include <iostream>
- using namespace std;
-
- class A
- {
- public:
- A()
- {
- cout << "A constructor" << endl;
- }
- };
-
- class B : public A
- {
- public:
- B()
- {
- cout << "B constructor" << endl;
- }
- };
-
- int main()
- {
- new B; // 如果是B b; 也会先后调用两个构造函数
- return 0;
- }
结果:
A constructor
B constructor
继续看:
- #include <iostream>
- using namespace std;
-
- class A
- {
- public:
- ~A()
- {
- cout << "A destructor" << endl;
- }
- };
-
- class B : public A
- {
- public:
- ~B()
- {
- cout << "B destructor" << endl;
- }
- };
-
- int main()
- {
- new B;
- return 0; // 程序结束后,不会调用任何析构函数
- }
继续看:
- #include <iostream>
- using namespace std;
-
- class A
- {
- public:
- ~A()
- {
- cout << "A destructor" << endl;
- }
- };
-
- class B : public A
- {
- public:
- ~B()
- {
- cout << "B destructor" << endl;
- }
- };
-
- int main()
- {
- B b;
- return 0; // 程序结束后,会先后调用B,A的析构函数
- }
继续看:
- #include <iostream>
- using namespace std;
-
- class A
- {
- public:
- ~A()
- {
- cout << "A destructor" << endl;
- }
- };
-
- class B : public A
- {
- public:
- ~B()
- {
- cout << "B destructor" << endl;
- }
- };
-
- int main()
- {
- B *pb = new B;
- delete pb; // 程序会先后调用B, A的析构函数
-
- return 0;
- }
关键的问题来了, 我们知道, C++中经常用到多态, 经常用基类指针指向派生类对象, 所以下面程序有bug:
- #include <iostream>
- using namespace std;
-
- class A
- {
- public:
- ~A()
- {
- cout << "A destructor" << endl;
- }
- };
-
- class B : public A
- {
- public:
- ~B()
- {
- cout << "B destructor" << endl;
- }
- };
-
- int main()
- {
- A *p = new B;
- delete p; // bug, 只调用到了基类A的析构函数, 不符合预期
-
- return 0;
- }
修改后为:
- #include <iostream>
- using namespace std;
-
- class A
- {
- public:
- virtual ~A()
- {
- cout << "A destructor" << endl;
- }
- };
-
- class B : public A
- {
- public:
- ~B()
- {
- cout << "B destructor" << endl;
- }
- };
-
- int main()
- {
- A *p = new B;
- delete p; // ok, 会先后调用B,A的析构函数
-
- return 0;
- }
可见, 析构函数通常要虚。如果不把析构函数设置为虚函数, 会不知不觉地引起很多错误, 比如最常见最可让人伤心的内存泄露