为什么下面的程序会崩溃?我有一个基类,其析构函数不是虚拟的,但子类的析构函数是虚拟的:
#include <iostream>
class Base {
public:
Base() {
std::cout << "Base::Base CTOR " << std::endl;
}
~Base() {
std::cout << "Base::Base DTOR " << std::endl;
}
};
class Child : public Base {
public:
Child(){
std::cout << "Child::Child CTOR " << std::endl;
}
virtual ~Child() {
std::cout << "Child::Child DTOR " << std::endl;
}
};
int main (int argc, char **argv) {
Base *ptr = new Child;
delete ptr;
}
最佳答案
您所观察到的称为“未定义行为”。如果您想通过 Base
指针在 Child
实例上调用 delete,请将 Base
的 dtor 设为虚拟。
来自 2003 年标准 5.3.5/3:
In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.
关于c++ - 基类析构函数不是虚函数,子类析构函数是虚函数,程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11183832/