C++之虛解構函式

來源:互聯網
上載者:User

標籤:

代碼一、
#include <iostream>using namespace std;class Base{public:    Base(){};    ~Base()    {        cout << "Base destructor." << endl;    };};class Derive : public Base{public:    Derive(){};    ~Derive()    {        cout << "Derive destructor." << endl;    };};int main(int argc, char **argv){    cout << "delete pBase" << endl;    Base *pBase = new Derive();    delete pBase;    cout << "delete pDerive" << endl;    Derive *pDerive = new Derive();    delete pDerive;    return 0;}

運行結果:

代碼二、
#include <iostream>using namespace std;class Base{public:    Base(){};    virtual ~Base()    {        cout << "Base destructor." << endl;    };};class Derive : public Base{public:    Derive(){};    ~Derive()    {        cout << "Derive destructor." << endl;    };};int main(int argc, char **argv){    cout << "delete pBase" << endl;    Base *pBase = new Derive();    delete pBase;    cout << "delete pDerive" << endl;    Derive *pDerive = new Derive();    delete pDerive;    return 0;}

運行結果:

結論:

基類的解構函式是為了,刪除指向衍生類別對象的基類指標時,會調用衍生類別的解構函式。

只要衍生類別解構函式被調用,之後必定調用基類的解構函式。

疑問:按照C++的記憶體布局,虛函數是由放在虛函數表中的函數指標指向的,由函數指標間接調用的。而且衍生類別中如果定義了虛函數,那麼虛函數表中相應存放指向基類虛函數的指標就會被指向衍生類別虛函數的指標替換。以此實現多態,即用基類指標調用衍生類別函數。

但是解構函式是特殊呢,因為衍生類別的解構函式和基類的解構函式並不重名,因此可能不是這樣處理的,此處還需要深究。

C++之虛解構函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.