【发布时间】:2016-10-10 02:45:36
【问题描述】:
尝试为单个链表类构建赋值运算符。我以为我正确构建了它,但仍然出现内存泄漏。
该类由一个 First 和 Last 变量组成。然后是 Node 结构。
Node 结构如下所示:
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;
}
编辑:
复制构造函数(工作):
// copy constructor
queue::queue(const queue &v){
if (v.first != NULL ) {
first = new node(*v.first);
first->next = NULL;
last = first;
// first-> value = v.first->value; // copy constructor should have done that
node *curr = first;
node *otherCur = v.first;
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;
}
}
工作的析构函数:
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;
【问题讨论】:
-
请发帖minimal reproducible example。真正的问题可能在任何地方,而不仅仅是您发布的代码。
-
我知道我的代码的其他部分没有内存泄漏,它特定于赋值运算符..已经测试过了..
-
@JoeCaraccio 你有工作拷贝构造函数吗?你有一个工作的析构函数吗?如果两者的答案都是“是”,那么赋值运算符是一个使用
copy / swap成语的 4 行函数。因此,如果您想要答案,请发布我提到的那些功能。 -
要求发minimal reproducible example 有两个目的: 1. 许多程序员能够在创建它的过程中找到它的问题和解决方案。 2. 如果 SO 用户能够获取并执行代码,您更有可能从 SO 用户那里获得帮助。
-
很明显赋值运算符坏了,即使不了解类的全部细节。首先,如果
this == &rhs那么,根据定义,什么都不应该发生。将对象分配给自身是无操作的。然而,代码消失并开始删除内容。这没有逻辑意义。否则,应该发生的是: 1. 该对象的链表被删除。 2. rhs对象的链表需要复制,复制的副本成为该对象的链表。无论从哪个角度看这段代码,都没有任何意义。
标签: c++ memory-leaks linked-list assignment-operator