C++数组多态以及元素析构顺序

610阅读 0评论2014-07-02 Wins0n
分类:C/C++

目的:
解释为何C++多态会崩溃

要点:
1. C++数组不支持多态
2. C++数组元素析构顺序为逆序析构,不管是在堆上还是在栈上;

示例代码:

点击(此处)折叠或打开

  1. #include <iostream>
  2. using namespace std;

  3. class Base
  4. {
  5. public:
  6.     virtual ~Base()
  7.     {
  8.         cout << "Base::~Base()" << endl;
  9.     }
  10. };

  11. class Derived : public Base
  12. {
  13. private:
  14.     int flag;
  15. public:
  16.     ~Derived()
  17.     {
  18.         cout << "Derived::~Derived()" << endl;
  19.     }
  20. };

  21. class Test
  22. {
  23. public:
  24.     ~Test()
  25.     {
  26.         cout << "Test::~Test() " << hex << this << endl;
  27.     }
  28. };

  29. int main(int argc, char **argv)
  30. {
  31.     //Base *p = new Derived[10];
  32.     //delete []p;

  33.     cout << "new/delete" << endl;
  34.     Test *pArr = new Test[10];
  35.     delete []pArr;

  36.     cout << "local array" << endl;
  37.     Test test[10];

  38.     return 0;
  39. }

解释:
对于最后一个元素,实际上是个Derived对象,而通过Base指针,认为大小为sizeof(Base),这样去获取虚表调用析构函数就造成了core dump,也就是一个元素都没办法析构成功。

参考:

http://blog.csdn.net/fullsail/article/details/6290568
上一篇:中缀表达式求值
下一篇:CLRS 6.5-6