delete[] an array of objects

无人久伴 提交于 2019-11-26 09:35:12

问题


I have allocated and array of Objects

Objects *array = new Objects[N];

How should I delete this array? Just

delete[] array;

or with iterating over the array\'s elements?

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

Thanks

UPDATE:

I changed loop body as

delete &array[i];

to force the code to compile.


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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.




回答5:


delete [] array

is enough.



来源:https://stackoverflow.com/questions/2486034/delete-an-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!