C++ delete[] 对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2486034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
delete[] an array of objects
提问by osgx
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.
强制编译代码。
回答by jamesdlin
Every use of new
should be balanced by a delete
, and every use of new[]
should be balanced by delete[]
.
每次使用new
都应由 a 平衡delete
,每次使用new[]
都应由 平衡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 erroris 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.
顺便说一句,强制性的:避免分配数组new[]
;改用使用std::vector
,然后它的析构函数将为您处理清理工作。此外,如果抛出异常,它不会泄漏内存,从而是异常安全的。
回答by Naveen
Just delete[] array
is sufficient. It is guaranteed that each element of the array is deleted when you delete an array using delete[]
operator.
只要delete[] array
是足够的。使用delete[]
运算符删除数组时,保证删除数组的每个元素。
回答by sth
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.
作为一般规则,您应该delete
/delete[]
正是您用new
/分配的那些东西new[]
。在这种情况下,您使用 进行了一次分配new[]
,因此您应该使用一次调用来delete[]
再次释放分配的内容。
That the delete
s in the for-loop won't compile is also a good indication that they are not the right way to do it.
delete
for 循环中的s 不会编译也是一个很好的迹象,表明它们不是正确的方法。
回答by Michael Burr
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.
将删除操作未返回的内容new
。
Not to mention that the subsequent delete[] array;
will call the destructor for all the objects that just had destructors called in the loop.
更不用说后续delete[] array;
会为所有刚刚在循环中调用析构函数的对象调用析构函数。
So don't do that.
所以不要那样做。
回答by vava
delete [] array
is enough.
足够。