C++ C++;链表赋值运算符
正在尝试为单个链表类生成赋值运算符。我认为我构建的是正确的,但仍然存在内存泄漏 该类由第一个和最后一个变量组成。然后是一个节点结构 节点结构如下所示:C++ C++;链表赋值运算符,c++,memory-leaks,linked-list,assignment-operator,C++,Memory Leaks,Linked List,Assignment Operator,正在尝试为单个链表类生成赋值运算符。我认为我构建的是正确的,但仍然存在内存泄漏 该类由第一个和最后一个变量组成。然后是一个节点结构 节点结构如下所示: struct node { TYPE value; node * next; node * last; }; 我的赋值运算符看起来像这样,它仍然有内存泄漏 queue& queue::operator=(const queue &rhs){ if(this == &rhs
struct node
{
TYPE value;
node * next;
node * last;
};
我的赋值运算符看起来像这样,它仍然有内存泄漏
queue& queue::operator=(const queue &rhs){
if(this == &rhs ){
node *ptr = first;
node *temp;
while(ptr != NULL){
temp = ptr;
ptr = ptr->next;
delete temp; // release the memory pointed to by temp
}
delete ptr;
} else{
if (rhs.first != NULL ) {
first = new node(*rhs.first);
first->next = NULL;
last = first;
// first-> value = v.first->value; // copy constructor should have done that
node *curr = first;
node *otherCur = rhs.first;
node *ptr = first;
node *temp;
while(ptr != NULL){
temp = ptr;
ptr = ptr->next;
delete temp; // release the memory pointed to by temp
}
while(otherCur->next != NULL){
curr->next = new node(*otherCur->next);
curr->next->next = NULL;
last = curr->next;
// curr->next->value = otherCur->next->value;
curr = curr->next;
otherCur = otherCur->next;
}
// curr->next = NULL;
}
}
return *this;
}
编辑:
复制构造函数(工作):
工作析构函数:
queue::~queue(){
node *ptr = first;
node *temp;
while(ptr != NULL){
temp = ptr;
ptr = ptr->next;
delete temp; // release the memory pointed to by temp
}
}
.H文件的成员变量:
private:
// fill in here
node * first;
node * last;
如果您有一个工作的复制构造函数和析构函数,则可以使用
copy/swap
轻松实现赋值运算符,而不是所有这些代码
#include <algorithm>
//...
queue& queue::operator=(const queue& v)
{
queue temp(v);
std::swap(temp.first, first);
std::swap(temp.last, last);
return *this;
}
#包括。请发布一篇文章。真正的问题可能在任何地方,而不仅仅是你发布的代码。我知道我代码的其他部分没有内存泄漏,它是特定于赋值运算符的。。已经测试过了。@JoeCaraccio您是否有可用的副本构造函数?你们有工作的析构函数吗?如果两者的答案都是“是”,则赋值运算符是一个使用copy/swap
习惯用法的4行函数。所以,如果你想得到答案,就发布我提到的那些函数。许多程序员能够在创建过程中找到问题和解决方案。2.如果SO用户能够获取代码并执行它,则您更有可能从SO用户那里获得帮助。很明显,赋值运算符已损坏,即使不了解类的全部细节。首先,如果this==&rhs
,那么根据定义,什么都不应该发生。将一个对象分配给它自己是不允许的。但是,代码会自动关闭并开始删除内容。这没有逻辑意义。否则,应该是:1。此对象的链接列表将被删除。2.rhs对象的链接列表需要复制,复制副本将成为此对象的链接列表。无论我从哪个角度看代码,它都没有任何意义。你让我今天过得很开心。。哇,这是一个更好的解决方案。谢谢你!
#include <algorithm>
//...
queue& queue::operator=(const queue& v)
{
queue temp(v);
std::swap(temp.first, first);
std::swap(temp.last, last);
return *this;
}