删除[]对象的数组 [英] delete[] an array of objects
问题描述
我已经分配的对象和数组
I have allocated and array of Objects
Objects *array = new Objects[N];
我应该如何删除这个数组?
刚
How should I delete this array? Just
delete[] array;
或遍历数组的元素?
for(int i=0;i<N;i++)
delete array[i];
delete[];
感谢
更新:
我改变循环体为
delete &array[i];
要强制code编译。
推荐答案
每一个使用新
应该由被平衡删除
,每使用新[]
应该由平衡删除[]
。
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;
}
这是你原来的code送给你的编译错误事实的是,你做错了什么强烈暗示。
The fact that your original code gave you a compilation error is a strong hint that you're doing something wrong.
顺便说一句,强制性的:避免与分配阵列新[]
;使用的std ::矢量
代替,然后将其析构函数会照顾清理你。此外,它会异常安全通过,如果引发异常没有内存泄漏。
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.
这篇关于删除[]对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!