c++ - 虚拟析构函数 : Not Working?

标签 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

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

  delete p; 
  }

最佳答案

是的,你只是看不到输出,因为你打错了:

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

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

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

关于c++ - 虚拟析构函数 : Not Working?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18056106/

相关文章:

c++ - 虚拟析构函数改变 decltype 的行为

c++ - Destructor间接调用虚函数

c++ - 基类指针与继承类指针?

c++ - 包括 <exception> header C++

c++ - 指向空指针

c++ - 授予另一个类访问特定方法的权限

c++ - Visual C++ 2010,右值引用错误?

c++ - C++中的析构函数概念

c++ - 为什么抽象类的默认析构函数不是虚拟的?

C++11接口(interface)纯虚析构函数