我是否需要显式调用基本虚拟析构函数?
当用C ++重写一个类(用一个虚拟析构函数)时,我在inheritance类上再次实现了析构函数,但是是否需要调用基类析构函数?
如果是的话,我想像是这样的…
MyChildClass::~MyChildClass() // virtual in header { // Call to base destructor... this->MyBaseClass::~MyBaseClass(); // Some destructing specific to MyChildClass }
我对吗?
不,按相反的顺序自动调用析构函数。 (基类最后)。 不要调用基类析构函数。
不,您不需要调用基本析构函数,派生析构函数总是会调用基本析构函数。 请参阅我的相关答案在这里销毁的顺序 。
要理解为什么你想在基类中使用虚析构函数,请看下面的代码:
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()。
别人说什么,但也要注意,你不必在派生类中声明析构函数。 一旦你声明一个析构函数是虚拟的,就像你在基类中所做的那样,所有派生的析构函数都将是虚拟的,不pipe你是否声明它们。 换一种说法:
struct A { virtual ~A() {} }; struct B : public A { virtual ~B() {} // this is virtual }; struct C : public A { ~C() {} // this is virtual too };
与其他虚拟方法不同,在Derived中显式调用Base方法来“调用”这个调用,编译器会生成代码,以相反的顺序调用析构函数,调用它们的构造函数。
不,它会自动调用。
它总是像其他人指出的那样自动调用,但这里是结果的概念validation:
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 . . .
如果将基类析构函数设置为虚拟的,那么结果与案例1和2相同。