【发布时间】:2014-09-14 20:51:29
【问题描述】:
以下代码实现了一个简单的哈希函数。我已经使用 new 运算符分配了结构实例。
程序结束时我是否使用了delete 运算符?
如果是这样,我该怎么做? [每个结构实例的delete 语句?或者有更简单的方法吗? ]
#include <iostream>
#define SIZE 10
using namespace std;
typedef struct myhashtag
{
int data;
struct myhashtag * next;
} myhash;
void printhash(myhash array[])
{
// print fn
}
void hash(int data, myhash array[])
{
int h = data % SIZE;
myhash * newhash = new myhash;
newhash->data = data;
newhash->next = NULL;
if(array[h].next == NULL) //first insert
{
array[h].next = newhash;
return;
}
myhash * iter = array[h].next;
while(iter->next != NULL)
{
iter = iter->next;
}
iter->next = newhash;
return;
}
int main()
{
myhash array[SIZE];int i;
for(i=0; i<SIZE; i++)
{
array[i].data = 0;
array[i].next = NULL;
}
while(1)
{
cout << "\nSo, what would you like to enter? : ";
cin >> i;
hash(i, array);
printhash(array);
}
// the deletes go here
return 0;
}
【问题讨论】:
-
每个发出的
new()都应该有一个随附的delete声明。 '对于结构的每个实例都有一个delete语句?' 是的,除了使用myhash array[SIZE];自动创建的那些。 -
在处理大项目时,每个
new运算符都需要使用delete!否则你会耗尽内存! -
但实际上您应该使用像
std::shared_ptr这样的内存管理设备,这样就不需要new和delete。 -
@Sathish 如果有人可以对 cmets 投反对票,我只会对你的第一句话投反对票。这只是不好的做法,可能会让人们养成总是忘记它的习惯。此外,一些项目可能从小型应用程序开始,并意外地(重新)用于更大的应用程序。然后你就会面临追踪所有动态分配的维护噩梦......
-
@anderas 实际上,他的陈述是 100% 正确的。智能指针是这样做的一种方法,在某些情况下这是一个很好的解决方案(但可能不是在这里——他需要将他的哈希表包装在一个更大的函数中来管理它的内存)。
标签: c++ memory-management memory-leaks destructor