簡體   English   中英

我需要顯式調用基本虛擬析構函數嗎?

[英]Do I need to explicitly call the base virtual destructor?

當在 C++ 中覆蓋 class 時(使用虛擬析構函數),我在繼承 class 上再次將析構函數實現為虛擬,但是我需要調用基析構函數嗎?

如果是這樣,我想它是這樣的......

MyChildClass::~MyChildClass() // virtual in header
{
    // Call to base destructor...
    this->MyBaseClass::~MyBaseClass();

    // Some destructing specific to MyChildClass
}

我對嗎?

不,析構函數會以與構造相反的順序自動調用。 (最后是基類)。 不要調用基本 class 析構函數。

不,您不需要調用基析構函數,派生析構函數始終為您調用基析構函數。 請在此處查看我的相關答案以了解銷毀順序

要了解為什么要在基礎 class 中使用虛擬析構函數,請參閱以下代碼:

class B
{
public:
    virtual ~B()
    {
        cout<<"B destructor"<<endl;
    }
};


class D : public B
{
public:
    virtual ~D()
    {
        cout<<"D destructor"<<endl;
    }
};

當你這樣做時:

B *pD = new D();
delete pD;

然后,如果您在 B 中沒有虛擬析構函數,則只會調用 ~B()。 但是因為你有一個虛擬析構函數,所以首先調用~D(),然后調用~B()。

其他人所說的,但還要注意,您不必在派生的 class 中聲明析構函數 virtual。 一旦你聲明了一個虛擬的析構函數,就像你在基礎 class 中所做的那樣,無論你是否聲明它們,所有派生的析構函數都將是虛擬的。 換句話說:

struct A {
   virtual ~A() {}
};

struct B : public A {
   virtual ~B() {}   // this is virtual
};

struct C : public A {
   ~C() {}          // this is virtual too
};

不。與其他虛擬方法不同,您會從 Derived 顯式調用 Base 方法以“鏈接”調用,編譯器生成代碼以按照調用構造函數的相反順序調用析構函數。

不,您永遠不會調用基本 class 析構函數,它總是像其他人指出的那樣自動調用,但這里是概念證明和結果:

class base {
public:
    base()  { cout << __FUNCTION__ << endl; }
    ~base() { cout << __FUNCTION__ << endl; }
};

class derived : public base {
public:
    derived() { cout << __FUNCTION__ << endl; }
    ~derived() { cout << __FUNCTION__ << endl; } // adding call to base::~base() here results in double call to base destructor
};


int main()
{
    cout << "case 1, declared as local variable on stack" << endl << endl;
    {
        derived d1;
    }

    cout << endl << endl;

    cout << "case 2, created using new, assigned to derive class" << endl << endl;
    derived * d2 = new derived;
    delete d2;

    cout << endl << endl;

    cout << "case 3, created with new, assigned to base class" << endl << endl;
    base * d3 = new derived;
    delete d3;

    cout << endl;

    return 0;
}

output 是:

case 1, declared as local variable on stack

base::base
derived::derived
derived::~derived
base::~base


case 2, created using new, assigned to derive class

base::base
derived::derived
derived::~derived
base::~base


case 3, created with new, assigned to base class

base::base
derived::derived
base::~base

Press any key to continue . . .

如果您將基本 class 析構函數設置為虛擬的,那么案例 3 的結果將與案例 1 和 2 相同。

不,它是自動調用的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM