使用析构函数释放链接对象 [英] Using the destructor to free linked objects
问题描述
我有一个名为node的类。我将一堆节点对象链接在一起以形成链表。当节点析构函数被调用时,它只删除第一个节点。如何迭代整个链接的节点列表并删除每个节点对象?
I have a class called "node". I link a bunch of node objects together to form a linked list. When the "node" destructor is called, it only deletes the first node. How do I iterate through the entire linked list of nodes and delete each node object?
这里是类定义:
class Node
{
private:
double coeff;
int exponent;
Node *next;
public:
Node(double c, int e, Node *nodeobjectPtr)
{
coeff = c;
exponent = e;
next = nodeobjectPtr;
}
~Node()
{
printf("Node Destroyed");
}
通过在指向第一个节点的指针上调用delete来调用析构函数链接节点列表。
The destructor is called by invoking delete on the pointer to the first node of the linked node list.
推荐答案
如何遍历整个节点链表,节点对象?
How do I iterate through the entire linked list of nodes and delete each node object?
这将是 cleaner ,如果你有一个单独的类来管理整个列表,这样节点可以是简单的数据结构。然后你只需要一个简单的循环列表的析构函数:
It would be cleaner if you had a separate class to manage the entire list, so that nodes can be simple data structures. Then you just need a simple loop in the list's destructor:
while (head) {
Node * victim = head;
head = victim->next; // Careful: read this before deleting
delete victim;
}
如果你真的想将列表管理委托给节点本身,需要更加小心:
If you really want to delegate list management to the nodes themselves, you'll need to be a bit more careful:
while (next) {
Node * victim = next;
next = victim->next;
victim->next = nullptr; // Careful: avoid recursion
delete victim;
}
在此方案下,您还需要在删除节点时从列表中删除它后 - 再次,请确保您重置其指针,以便它不会删除列表的其余部分。这是另一个支持单独的列表类的原因。
Under this scheme, you'll also need to be careful when deleting a node after removing it from the list - again, make sure you reset its pointer so it doesn't delete the rest of the list. That's another reason to favour a separate "list" class.
这篇关于使用析构函数释放链接对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!