博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
removing objects from an array
阅读量:7046 次
发布时间:2019-06-28

本文共 1113 字,大约阅读时间需要 3 分钟。

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://tcuol.baihongyu.com/

你可能感兴趣的文章
搭建Go开发及调试环境(LiteIDE + GoClipse) -- Windows篇
查看>>
删除注释云平台JS,加快DISCUZ访问
查看>>
Flink -- Failover
查看>>
Android 多个Fragment嵌套导致的三大BUG
查看>>
你的身份信息已失效,请重新输入密码登录
查看>>
Gson、FastJson、json-lib对比与实例
查看>>
External component has thrown an exception
查看>>
使用JQuery获取被选中的checkbox的value值 以及全选、反选
查看>>
lua去掉字符串中的UTF-8的BOM三个字节
查看>>
CentOS下MySQL主从同步配置
查看>>
空暇时候思考2(&#39;\0&#39;等价于数字0还是字符0)
查看>>
Nginx/LVS/HAProxy负载均衡软件的优缺点详解
查看>>
Using Autorelease Pool Blocks
查看>>
[AWS vs Azure] 云计算里AWS和Azure的探究(2)
查看>>
MySQL字段数据全部查出【只保留中文、英文、数字、空格的词表】
查看>>
Zombie.js Insanely fast, headless full-stack testing using Node.js
查看>>
SpringMVC源码分析3:DispatcherServlet的初始化与请求转发
查看>>
Hyper-V故障转移群集搭建(3)
查看>>
VMware下ubuntu上网设置(二)
查看>>
sqlplus的session下无法使用退格键的问题处理
查看>>