【发布时间】:2023-03-23 21:47:01
【问题描述】:
我正在尝试在 C++ 中实现一个单链表类。我重载了赋值运算符来克隆列表。克隆本身似乎工作正常,但程序在删除克隆列表期间崩溃,这让我怀疑在复制过程中是否有问题。
非常感谢任何帮助。 下面是重载 = 运算符的代码:
DLList& DLList::operator=(const DLList& iList)
{
Node *t = iList.head();
while(t != NULL)
{
push(t->data);
t = t->next;
}
return *this;
}
这是推送操作的代码:
void DLList::push(int data)
{
Node *n = new Node;
n->data = data;
n->next = NULL;
//n->random = NULL;
n->next = _head;
_head = n;
//cout << "_head" <<_head->data<< "head->next" << (_head->next ? _head->next->data : 0)<<endl;
}
这是主要代码(崩溃发生的地方):
DLList *d = new DLList();
d->push(10);
d->push(20);
d->push(30);
d->push(40);
d->setRandom();
d->display("Original list"); // Displays the original list fine
DLList *d1 = new DLList();
d1 = d;
d1->display("Cloned list"); //Displays the cloned list fine
delete d; // works fine
delete d1; // Crashes here due to segmentation fault, invalid pointer access during delete called as part of destructor)
析构函数代码(如果有帮助的话):
~DLList()
{
while(_head != NULL)
{
Node *temp = _head;
_head = _head->next;
delete temp; // crashes here during first iteration for the cloned list
}
}
【问题讨论】:
-
怀疑问题出在复制运算符上。您需要复制列表拥有的每个对象。你能显示代码吗?
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行逐行检查您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
另一个问题(答案没有涉及)是您的赋值运算符附加到当前列表而不是替换它。
标签: c++ linked-list singly-linked-list