1

嘿,为什么在这个程序结束时调用了两次基本析构函数?

#include <iostream>
using namespace std;

class B{
public:
  B(){
    cout << "BC" << endl; x = 0;
  }
  virtual ~B(){
    cout << "BD" << endl;
  }
  void f(){
    cout << "BF" << endl;
  }
  virtual void g(){
    cout << "BG" << endl;
  }
private:
  int x;
};

class D: public B{
public:
  D(){
    cout << "dc" << endl; y = 0;
  }
  virtual ~D(){
    cout << "dd" << endl;
  }
  void f(){
    cout << "df" << endl;
  }
  virtual void g(){
    cout << "dg" << endl;
  }
private:
  int y;
};

int main(){
  B b, * bp = &b;
  D d, * dp = &d;
  bp->f();
  bp->g();
  bp = dp;
  bp->f();
  bp->g();
}
4

2 回答 2

4

Destructors are called in order, as if they were unwinding the effects of the corresponding constructors. So, first the destructors of the derived objects, then the destructors of the base objects. And making the destructors virtual doesn't have any impact on calling / not calling the base class destructor.

Also to mention, your example could be simplified this way (this code also results in calling the base destructor twice and the derived destructor once):

struct A {
   ~A() {
      // ...
   }
};

struct B: A {
   ~B() {
      // ...
   }
};

int main() {
   A a;
   B b;
}
于 2010-06-05T13:14:20.913 回答
3

一次为 b 调用一次,一次为 d 调用

注意当D的析构函数被调用时,它会自动调用B的析构函数,它不同于普通的虚函数。您需要显式调用基类函数才能使用它。

于 2010-06-05T12:53:20.050 回答