Ste*_*cob 1 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
Run Code Online (Sandbox Code Playgroud)
删除应该在类B中调用虚拟析构函数,但它不会.
delete p;
}
Run Code Online (Sandbox Code Playgroud)
确实如此,你只是看不到输出,因为你有一个拼写错误:
cout < "1000 ints deleted\n";
// ^, less than
Run Code Online (Sandbox Code Playgroud)
你的编译器过于宽松,不应该编译(至少在C++ 11中).
它可能是因为basic_ios::operator void*使得流对象可以隐式转换为,void*并且您的编译器允许字符串文字衰减到char*(可转换为void*).cout < "x";然后简单地使用内置指针进行比较,operator<(void*, void*)并抛弃结果.