virtual析構函數的作用?

大家知道,析構函數是爲了在對象不被使用之後釋放它的資源,虛函數是爲了實現多態。那麼把析構函數聲明爲vitual有什麼作用呢?請看下面的代碼:
1         #include
2       using namespace std;
3
4       class Base
5       {
6       public:
7                Base() {};       //Base的構造函數
8               ~Base()        //Base的析構函數
9                {
10                       cout << "Output from the destructor of class Base!" << endl;
11              };
12              virtual void DoSomething() 
13              {
14                       cout << "Do something in class Base!" << endl;
15              };
16     };
17    
18     class Derived : public Base
19     {
20     public:
21              Derived() {};     //Derived的構造函數
22              ~Derived()      //Derived的析構函數
23              {
24                       cout << "Output from the destructor of class Derived!" << endl;
25              };
26              void DoSomething()
27              {
28                       cout << "Do something in class Derived!" << endl;
29              };
30     };
31    
32     int main()
33     {
34              Derived *pTest1 = new Derived();   //Derived類的指針
35              pTest1->DoSomething();
36              delete pTest1;
37    
38              cout << endl;
39    
40              Base *pTest2 = new Derived();      //Base類的指針
41              pTest2->DoSomething();
42              delete pTest2;
43    
44              return 0;
45     }
先看程序輸出結果:
1       Do something in class Derived!
2       Output from the destructor of class Derived!
3       Output from the destructor of class Base!
4      
5       Do something in class Derived!
6       Output from the destructor of class Base!
代碼第36行可以正常釋放pTest1的資源,而代碼第42行沒有正常釋放pTest2的資源,因爲從結果看Derived類的析構函數並沒有被調用。通常情況下類的析構函數裏面都是釋放內存資源,而析構函數不被調用的話就會造成內存泄漏。原因是指針pTest2是Base類型的指針,釋放pTest2時只進行Base類的析構函數。在代碼第8行前面加上virtual關鍵字後的運行結果如下:
1       Do something in class Derived!
2       Output from the destructor of class Derived!
3       Output from the destructor of class Base!
4      
5       Do something in class Derived!
6       Output from the destructor of class Derived!
7       Output from the destructor of class Base!
此時釋放指針pTest2時,由於Base的析構函數是virtual的,就會先找到並執行Derived類的析構函數,然後再執行Base類的析構函數,資源正常釋放,避免了內存泄漏。
因此,只有當一個類被用來作爲基類的時候,纔會把析構函數寫成虛函數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章