removing objects from an array

简介:

I am creating a program that uses an array of objects declared with

Element* elements =newElement[number];

where an element is a class that has/needs a its own destructor.

when I go to delete this would I use just use array delete, and have the program worry about calling the destructor:

delete[] elements;

or do I call the destructor for each item explicitly with keyword delete:

for ( int  ii =0; ii<ArraySize; ii++)
     delete  elements[ii];
delete [] elements;

Note: I understand that I could probably use something like boost::ptr_vector, but I wanted similar to hashTable functionality (so the for loop would need additional information, but that is outside of the direct scope of this question) which is why I am using a traditional array. I would still like to know which behavior is needed to avoid memory leaks.

解答:

第一个是正确的,第二个会得到编译错误。

这个问题主要的问题其实是对于多位数组的动态内存分配的问题。比如我们不能直接使用int* p=new int[4][3];等的的。

而是应该借鉴下面的例子:

1
2
3
elements =  new  Element *[rows];
for  ( int  i=0; i<rows; i++)
     elements[i] =  new  Element[row_len];

  然后采用:

1
2
3
for  ( int  i=0; i<rows; i++)
     delete  [] elements[i];
delete  [] elements;

  原文地址:http://stackoverflow.com/questions/10425354/removing-objects-from-an-array


==============================================================================
本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2012/05/03/2480881.html,如需转载请自行联系原作者

相关文章
|
JavaScript 测试技术
【若川视野 x源码共读】第33期 | arrify 转数组 Convert a value to an array
mac: 在github代码仓库页面通过快捷键 command + k,再在文本框中输入 &quot;&gt;&quot;,即可查看到在线打开的命令行
131 0
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
|
Java
[LeetCode]Degree of an Array 数组的度
链接:https://leetcode.com/problems/degree-of-an-array/description/难度:Easy题目:697.
1057 0
|
机器学习/深度学习 人工智能
|
2月前
|
测试技术 PHP 开发者
PHP 数组查找:为什么 `isset()` 比 `in_array()` 快得多?
PHP 数组查找:为什么 `isset()` 比 `in_array()` 快得多?
|
6月前
|
人工智能 Java
Java 中数组Array和列表List的转换
本文介绍了数组与列表之间的相互转换方法,主要包括三部分:1)使用`Collections.addAll()`方法将数组转为列表,适用于引用类型,效率较高;2)通过`new ArrayList&lt;&gt;()`构造器结合`Arrays.asList()`实现类似功能;3)利用JDK8的`Stream`流式计算,支持基本数据类型数组的转换。此外,还详细讲解了列表转数组的方法,如借助`Stream`实现不同类型数组间的转换,并附带代码示例与执行结果,帮助读者深入理解两种数据结构的互转技巧。
320 1
Java 中数组Array和列表List的转换
|
6月前
|
JavaScript 前端开发 API
JavaScript中通过array.map()实现数据转换、创建派生数组、异步数据流处理、复杂API请求、DOM操作、搜索和过滤等,array.map()的使用详解(附实际应用代码)
array.map()可以用来数据转换、创建派生数组、应用函数、链式调用、异步数据流处理、复杂API请求梳理、提供DOM操作、用来搜索和过滤等,比for好用太多了,主要是写法简单,并且非常直观,并且能提升代码的可读性,也就提升了Long Term代码的可维护性。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
9月前
|
存储 Go 索引
go语言中的数组(Array)
go语言中的数组(Array)
190 67

热门文章

最新文章