我是否須要顯式調用基本虛擬析構函數?

當用C ++覆蓋一個類(使用虛擬析構函數)時,我在繼承類上再次將析構函數實現爲虛擬,可是我是否須要調用基本析構函數? 函數

若是是這樣,我想它就是這樣...... this

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

    // Some destructing specific to MyChildClass
}

我對嗎? spa


#1樓

不,你永遠不會調用基類析構函數,它老是像其餘人指出的那樣自動調用,但這裏是結果的概念證實: code

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;
}

輸出是: 繼承

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 . . .

若是將基類析構函數設置爲虛擬的,那麼案例3的結果將與案例1和2相同。 ci


#2樓

不,您不須要調用基礎析構函數,派生析構函數老是爲您調用基礎析構函數。 請在此處查看個人相關答案以瞭解銷燬順序get

要了解爲何要在基類中使用虛擬析構函數,請參閱如下代碼: it

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


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

當你這樣作時: io

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

而後,若是B中沒有虛擬析構函數,則只調用~B()。 可是由於你有一個虛擬的析構函數,因此先調用~D()而後調用~B()。 class


#3樓

不,它是自動調用的。


#4樓

不,析構函數會按照相反的構造順序自動調用。 (基礎課最後)。 不要調用基類析構函數。


#5樓

其餘人說了什麼,但也注意到你沒必要在派生類中聲明析構函數virtual。 一旦聲明瞭析構函數virtual,就像在基類中那樣,全部派生的析構函數都是虛擬的,不管你是否聲明它們。 換一種說法:

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

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

struct C : public A {
   ~C() {}          // this is virtual too
};
相關文章
相關標籤/搜索