目的:
解释为何C++多态会崩溃
要点:
1. C++数组不支持多态
2. C++数组元素析构顺序为逆序析构,不管是在堆上还是在栈上;
示例代码:
-
#include <iostream>
-
using namespace std;
-
-
class Base
-
{
-
public:
-
virtual ~Base()
-
{
-
cout << "Base::~Base()" << endl;
-
}
-
};
-
-
class Derived : public Base
-
{
-
private:
-
int flag;
-
public:
-
~Derived()
-
{
-
cout << "Derived::~Derived()" << endl;
-
}
-
};
-
-
class Test
-
{
-
public:
-
~Test()
-
{
-
cout << "Test::~Test() " << hex << this << endl;
-
}
-
};
-
-
int main(int argc, char **argv)
-
{
-
//Base *p = new Derived[10];
-
//delete []p;
-
-
cout << "new/delete" << endl;
-
Test *pArr = new Test[10];
-
delete []pArr;
-
-
cout << "local array" << endl;
-
Test test[10];
-
-
return 0;
-
}
解释:
对于最后一个元素,实际上是个Derived对象,而通过Base指针,认为大小为sizeof(Base),这样去获取虚表调用析构函数就造成了core dump,也就是一个元素都没办法析构成功。
参考:
http://blog.csdn.net/fullsail/article/details/6290568
阅读(602) | 评论(0) | 转发(0) |