C++ 链表的析构函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15672812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Destructor for a linked List
提问by user1665569
I have a linked_list and currently my destructor is not working properly. Not entirely sure why. Can somebody explain me how to solve this?
我有一个linked_list,目前我的析构函数不能正常工作。不完全确定为什么。有人可以解释我如何解决这个问题吗?
class linked_list {
private:
struct node
{
// String in this node
std::string data;
// Pointer to next node
struct node *next;
};
//First item in the list
struct node *first;
Here is my destructor
这是我的析构函数
linked_list::~linked_list(void)
{
while (first)
{
delete first;
first = first->next;
}
}
回答by Mohamad Ali Baydoun
The problem lies here:
问题出在这里:
delete first;
first = first->next;
When you delete first
, but then try to access first->next
. Cache first->next
into a temp variable of type node*
, then do delete first
to fix this:
当你删除后first
,再尝试访问first->next
。缓存first->next
到一个类型的临时变量中node*
,然后delete first
解决这个问题:
struct node* temp;
while (first != NULL)
{
temp = first->next;
delete first;
first = temp;
}
回答by HenryLok
change to
改成
linked_list::~linked_list(void)
{
struct node *next;
while (first != NULL)
{
next = first->next;
delete first;
first = next;
}
}
回答by pranav prakasan
When you 'delete' first, you actually clear all the links from it. Now, if you try to access some other node using this, will not produce the required result.
当您首先“删除”时,实际上是清除了其中的所有链接。现在,如果您尝试使用它访问某个其他节点,将不会产生所需的结果。
First, you have to point that node with some other pointer, so that you still have some link which you can access later.
首先,您必须使用其他指针指向该节点,以便您仍有一些稍后可以访问的链接。