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

目录
相关文章
|
5月前
|
开发者 Python
【Python】已解决:TypeError: descriptor ‘index‘ for ‘list‘ objects doesn‘t apply to a ‘str‘ object
【Python】已解决:TypeError: descriptor ‘index‘ for ‘list‘ objects doesn‘t apply to a ‘str‘ object
134 0
|
6月前
|
Python
【已解决】AttributeError: ‘Index‘ object has no attribute ‘to_list‘
【已解决】AttributeError: ‘Index‘ object has no attribute ‘to_list‘
|
7月前
|
索引
(详解)Object.keys() Object.values() Object.entries()
(详解)Object.keys() Object.values() Object.entries()
49 1
HalconDotNet.HTupleAccessException:“‘Cannot convert to double array‘ when accessing ‘HalconDotNet.HT
HalconDotNet.HTupleAccessException:“‘Cannot convert to double array‘ when accessing ‘HalconDotNet.HT
AttributeError: ‘list‘ object has no attribute ‘ndim‘
AttributeError: ‘list‘ object has no attribute ‘ndim‘
193 0
|
索引
Array.forEach()
Array.forEach()
85 0
|
编解码 搜索推荐 算法
Data-Data Objects and Attribute Types| 学习笔记
快速学习 Data-Data Objects and Attribute Types。
Data-Data Objects and Attribute Types| 学习笔记
|
Python
AttributeError: 'list' object has no attribute 'ndim'
AttributeError: 'list' object has no attribute 'ndim'
540 0
TypeError: cannot concatenate ‘str‘ and ‘list‘ objects
TypeError: cannot concatenate ‘str‘ and ‘list‘ objects
成功解决AttributeError: ‘dict_values‘ object has no attribute ‘index‘
成功解决AttributeError: ‘dict_values‘ object has no attribute ‘index‘