cpp中delete数组

例1:

#include <iostream>
using namespace std;
class A {
public:
   A() { cout << "constructor" << endl; }
   ~A() { cout << "desconstructor" << endl; }
};

int main() {
   A* p = new A[3] ;
   delete[] p;
}

输出:

constructor constructor constructor desconstructor desconstructor desconstructor

结论:正确释放内存。

例2:

    #include <iostream>

    using namespace std;

    class A { 
    public:
        A() { cout << "constructor" << endl; }
        ~A() { cout << "desconstructor" << endl; }
    };

    int main() {
        A** p = new A*[3] ;
        for(int i = 0; i < 3; i++)
          p[i] = new A;

        delete[] p;
    }

输出:

constructor constructor constructor

结论:没有如想象正确调用虚构函数

例3:

    #include <iostream>

    using namespace std;

    class A { 
    public:
        A() { cout << "constructor" << endl; }
        ~A() { cout << "desconstructor" << endl; }
    };

    int main() {
        A** p = new A*[3] ;
        for(int i = 0; i < 3; i++)
          p[i] = new A;
        for(int i = 0; i < 3; i++)
          delete p[i];

        delete[] p;
    }

输出:

constructor constructor constructor desconstructor desconstructor desconstructor

结论:正确调用虚构函数