C++中虛析構函數的作用


C++中的虛析構函數到底什么時候有用的,什么作用呢。

總的來說虛析構函數是為了避免內存泄露,而且是當子類中會有指針成員變量時才會使用得到的。也就說虛析構函數使得在刪除指向子類對象的基類指針時可以調用子類的析構函數達到釋放子類中堆內存的目的,而防止內存泄露的。

兩段代碼:

#include <iostream>

using namespace std;

class Base
{
public:
    Base(){}
    ~Base()
    {
        cout << "Base Destructor." << endl;
    }
private:
    int a, b;
};

class Derive : public Base
{
public:
    Derive()
    {
        
    }
    ~Derive()
    {
        cout << "Derive Destructor." << endl;
        // release memeory
        if(pI != NULL)
        {
            delete pI;
        }
    }
private:
    int *pI;
};

int main(void)
{
    {
        Base *pD = new Derive;
        delete pD;
    }
    int i;
    cin >> i;

    return 0;
}

運行結果:

這段代碼中沒有使用虛析構函數,當刪除動態申請的對象時,只執行了基類的構造函數,而此時,子類里面是有動態申請的內存的,那么這就早成了內存的泄露。

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class Base
 6 {
 7 public:
 8     Base(){}
 9     virtual ~Base()
10     {
11         cout << "Base Destructor." << endl;
12     }
13 private:
14     int a, b;
15 };
16 
17 class Derive : public Base
18 {
19 public:
20     Derive()
21     {
22         pI = new int;
23     }
24     ~Derive()
25     {
26         cout << "Derive Destructor." << endl;
27         // release memeory
28         if(pI != NULL)
29         {
30             delete pI;
31         }
32     }
33 private:
34     int *pI;
35 };
36 
37 int main(void)
38 {
39     {
40         Base *pD = new Derive;
41         delete pD;
42     }
43     int i;
44     cin >> i;
45 
46     return 0;
47 }

運行結果:

從運行結果可以看到,這次執行了基類的析構函數,那么就不會造成內存泄露了。

我的疑問:使用基類指針來操作子類對象實現了多態。也就說虛函數和指針組合實現了C++的多態性。但是那是子類函數與基類函數同名實現了重寫基類函數。而析構函數又不同名,難道也可以實現重寫么?

是不是因為每個類的析構函數只有一個,所以,C++內部對於析構函數做了特殊的處理,實現了所謂的重寫。

多態的實現是通過調用函數來實現的,但是delete是操作符,也可以么?也就說操作符操作基類指針,也會根據指針指向的實際對象來調用相應的函數么?

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM