虚拟析构函数:不工作?

时间:2013-08-05 10:35:59

标签: c++ virtual-destructor

我正在使用GNU编译器。 B类中的虚拟析构函数不会调用析构函数~D()。谁能告诉我为什么?

#include<iostream>
using namespace std;

class B {
  double* pd;
  public:
  B() {
  pd=new double [20];
  cout<< "20 doubles allocated\n";
  }

  virtual ~B() {   //the virtual destructor is not calling ~D()
  delete[] pd;
  cout<<"20 doubles deleted\n";
  }

  };

class D: public B {
  int* pi;
  public:
  D():B() {
  pi= new int [1000];
  cout<< "1000 ints allocated\n";
  }
  ~D() {
  delete[] pi;
  cout< "1000 ints deleted\n";
  }
  };

int main() {
  B* p= new D; //new constructs a D object

删除应该调用B类中的虚拟析构函数,但它不会。

  delete p; 
  }

1 个答案:

答案 0 :(得分:8)

确实如此,你只是看不到输出,因为你有一个拼写错误:

cout < "1000 ints deleted\n";
//   ^, less than

你的编译器过于宽松,不应该编译(至少在C ++ 11中)。

这可能是因为basic_ios::operator void*使得流对象可以隐式转换为void*,并且您的编译器允许字符串文字衰减到char*(可转换为void* )。 cout < "x";然后使用内置的operator<(void*, void*)进行指针比较并抛弃结果。