use*_*569 0 c++ destructor linked-list
我有一个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;
Run Code Online (Sandbox Code Playgroud)
这是我的析构函数
linked_list::~linked_list(void)
{
while (first)
{
delete first;
first = first->next;
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于:
delete first;
first = first->next;
Run Code Online (Sandbox Code Playgroud)
删除时first,然后尝试访问first->next.缓存first->next到类型的临时变量node*,然后delete first修复此问题:
struct node* temp;
while (first != NULL)
{
temp = first->next;
delete first;
first = temp;
}
Run Code Online (Sandbox Code Playgroud)