C++中析构函数可以是虚函数吗
对于使用 new 在自由存储区中实例化的派生类对象,如果将其赋给基类指针,
并通过该指针调用 delete,将不会调用派生类的析构函数。这可能导致资源未释放、内存泄露等问题,
必须引起重视。
要避免这种问题,可将析构函数声明为虚函数,如程序清单 11.4 所示
将析构函数声明为虚函数,确保通过基类指针调用 delete 时,将调用派生类的析
构函数
0: #include <iostream>
1: using namespace std;
2:
3: class Fish
4: {
5: public:
6: Fish()
7: {
8: cout << "Constructed Fish" << endl;
9: }
10: virtual ~Fish() // virtual destructor!
11: {
12: cout << "Destroyed Fish" << endl;
13: }
14: };
15:
16: class Tuna:public Fish
17: {
18: public:
19: Tuna()
20: {
21: cout << "Constructed Tuna” << endl;
22: }
23: ~Tuna()
24: {
25: cout << "Destroyed Tuna" << endl;
26: }
27: };
28:
29: void DeleteFishMemory(Fish* pFish)
30: {
31: delete pFish;
32: }
33:
34: int main()
35: {
36: cout << "Allocating a Tuna on the free store:" << endl;
37: Tuna* pTuna = new Tuna;
38: cout << "Deleting the Tuna: " << endl;
39: DeleteFishMemory(pTuna);
40:
41: cout << "Instantiating a Tuna on the stack:" << endl;
42: Tuna myDinner;
43: cout << "Automatic destruction as it goes out of scope: " << endl;
44:
45: return 0;
46: }
输出:
Allocating a Tuna on the free store:
Constructed Fish
Constructed Tuna
Deleting the Tuna:
Destroyed Tuna
Destroyed Fish
Instantiating a Tuna on the stack:
Constructed Fish
Constructed Tuna
Automatic destruction as it goes out of scope:
Destroyed Tuna
Destroyed Fish
分析:
相比于程序清单 11.3,程序清单 11.4 所做的唯一改进是,在第 10 行声明基类 Fish 的析构函数时,
添加了关键字 virtual。这个细微的修改导致将运算符 delete 用于 Fish 指针(如第 31 行所示)时,如果
该指针指向的是 Tuna 对象, 则编译器不仅会执行 Fish::~Fish( ), 还会执行 Tuna::~Tuna( )。 输出还表明,
无论 Tuna 对象是使用 new 在自由存储区中实例化的(第 37 行),还是以局部变量的方式在栈中实例化
的,构造函数和析构函数的调用顺序都相同。