我在 web site 上找到了这段代码
#include <iostream>
using namespace std;
struct Base
{
Base() { cout << "Base" << " "; }
virtual ~Base() { cout << "~Base" << endl; }
int i;
};
struct Der : public Base
{
Der() { cout << "Der" << endl; }
virtual ~Der() { cout << "~Der" << " "; }
int it[10]; // sizeof(Base) != sizeof(Der)
};
int main()
{
Base *bp = new Der;
Base *bq = new Der[5];
delete bp;
delete [] bq; // this causes runtime error
}
为什么会这样crash ?
最佳答案
Base *bq = new Der[5];
delete [] bq; // this causes runtime error
原因是数组没有多态。因此,在上面的代码中,delete
语句调用了未定义的行为。
§5.3.5/3 C++03 说
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. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.
您很幸运,它给出了运行时错误,并且您有机会尽快发现代码中的严重错误。
关于c++ - 虚拟析构函数使用数组失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7754532/