虚拟破坏者:不工作

Virtual Destructor: Not Working?

本文关键字:工作 破坏者 虚拟      更新时间:2023-10-16

我使用的是GNU编译器。类B中的虚拟析构函数不调用析构函数~D()。有人能告诉我为什么吗?

#include<iostream>
using namespace std;
class B {
  double* pd;
  public:
  B() {
  pd=new double [20];
  cout<< "20 doubles allocatedn";
  }
  virtual ~B() {   //the virtual destructor is not calling ~D()
  delete[] pd;
  cout<<"20 doubles deletedn";
  }
  };
class D: public B {
  int* pi;
  public:
  D():B() {
  pi= new int [1000];
  cout<< "1000 ints allocatedn";
  }
  ~D() {
  delete[] pi;
  cout< "1000 ints deletedn";
  }
  };
int main() {
  B* p= new D; //new constructs a D object

Delete应该调用类B中的虚拟析构函数,但它没有。

  delete p; 
  }

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

cout < "1000 ints deletedn";
//   ^, less than

你的编译器太宽容了,这不应该编译(至少在C++11中是这样)。

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