35

我已经分配了对象数组

Objects *array = new Objects[N];

我应该如何删除这个数组?只是

delete[] array;

或者迭代数组的元素?

for(int i=0;i<N;i++)
    delete array[i];
delete[];

谢谢

更新:

我将循环体更改为

delete &array[i];

强制代码编译。

4

5 回答 5

53

Every use of new should be balanced by a delete, and every use of new[] should be balanced by delete[].

for(int i=0;i<N;i++)
    delete array[i];
delete[] array;

That would be appropriate only if you initialized the array as:

Objects **array = new Objects*[N];
for (int i = 0; i < N; i++) { 
    array[i] = new Object;
}

The fact that your original code gave you a compilation error is a strong hint that you're doing something wrong.

BTW, obligatory: avoid allocating arrays with new[]; use std::vector instead, and then its destructor will take care of cleanup for you. Additionally it will be exception-safe by not leaking memory if exceptions are thrown.

于 2010-03-21T05:26:00.457 回答
18

Just delete[] array is sufficient. It is guaranteed that each element of the array is deleted when you delete an array using delete[] operator.

于 2010-03-21T05:19:37.197 回答
13

As a general rule you should delete/delete[] exactly those things that you allocated with new/new[]. In this case you have one allocation with new[], so you should use one call to delete[] to free that allocated thing again.

That the deletes in the for-loop won't compile is also a good indication that they are not the right way to do it.

于 2010-03-21T05:23:17.460 回答
9

Not only is

delete [] array;

enough, but if you do

for(int i=0;i<N;i++)
    delete &array[i];
delete[] array;

you'll be causing undefined behavior, because

delete &array[i];

will be deleting things that weren't returned by a new operation.

Not to mention that the subsequent delete[] array; will call the destructor for all the objects that just had destructors called in the loop.

So don't do that.

于 2010-03-21T05:25:50.223 回答
8
delete [] array

足够的。

于 2010-03-21T05:19:35.280 回答