我有一个带有链接的哈希表,其中每个节点都是:
struct Node
{
Object * objPtr;
Node * next;
}
当我从文件中读取数据时,我创建了一个对象:
...
Object * currObj;
currObj = new Object; //Causes memory leaks (doesn't get deleted)
//Save data
currObj->setData(data);
//Insertion
insert(*currObj);
这种情况下正确的析构函数是什么?我有一个用于表的析构函数和用于Object的析构函数,但是currObj = new Object
似乎会导致泄漏。
表析构函数:
//delete each chain
int i;
for (i = 0; i<capacity; i++)
{
Node * head = table[i];
Node * curr;
while (head)
{
curr = head->next;
head->next = NULL;
delete head;
head = curr;
}
}
//delete the array
delete[] table;
对象析构函数
if (name)
delete[] name;
if (location)
delete[] location;
//more if with data members
UPD - 插入
void Table::insert(Object & obj_)
{
char key[200];
char curr[100];
obj_.getKeywords(key); //Get keywords for the passed obj
char * token;
token = strtok(key, "?"); //Ge the first keyword
//Loop to add nodes for each keyword from the passed object
while (token != NULL)
{
int index = calculateIndex(token); //calculate index based of the
//first keyword
//Create new node
Node * newNode = new Node;
newNode->obj = &obj_;
newNode->next = NULL;
//Link node and table
newNode->next = table[index];
table[index] = newNode;
size++;
token = strtok(NULL, "?"); //Get next keyword
}
}
答案 0 :(得分:0)
你需要一个Node
的析构函数,它需要类似的东西:
Node::~Node()
{
if ( objPtr != NULL ) {
delete objPtr;
objPtr = NULL;
}
if ( next != NULL ) {
delete next;
next = NULL;
}
}
当表析构函数调用delete head
时,这就是调用Node
析构函数的时间。它默认会有一个析构函数,但不会专门释放/删除已分配的对象。