C++ 析構函數的調用順序


如果指針指向基類,但是指針在運行時指向派生類,則該基類必須具有虛擬析構函數,以便破壞派生類。如果沒有虛擬析構函數,則只會運行基類的析構函數。

比如:

Base* basePtr;

basePtr = new Derived(1);

如果沒有添加virtual,也就是沒有虛擬析構函數,看下面代碼示例:

#include <iostream>
using namespace std;

class Base
{
public:
    Base()
    {
        cout << "Base contruction" << endl;
    }
    ~Base()
    {
        cout << "Base deconstruction" << endl;
    }

};

class Derived : public Base
{
public:
    Derived()
    {
        cout << "Derived contruction " << endl;
    }
    ~Derived()
    {
        cout << "Derived deconstruction" << endl;
    }

};

int main()
{
    Base* basePtr;
    Derived* derevedPtr;

    basePtr = new Derived;
    delete basePtr;
}

則只會調用基類的析構函數

結果:

Base contruction
Derived contruction
Base deconstruction

在添加virtual之后,就會先用派生類的析構函數,再調用基類的析構函數

這樣添加:

virtual ~Base()

結果:

Base contruction
Derived contruction
Derived deconstruction
Base deconstruction

最后再提一下,如果指針是派生類聲明的,並且是指向派生類的,那么調用順序是基類構造->派生類構造->派生類析構->基類析構 

如果指針是基類聲明,並且指向基類的,那么調用順序是基類構造->基類析構

一些有用的blog:  Understanding warning C4265: class has virtual functions

 


免責聲明!

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



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