我正在使用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*)
并丢弃结果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句