C链接列表赋值运算符
作者:互联网
尝试为单个链表类构建赋值运算符.我以为我正确构建它,但仍然会出现内存泄漏.
该类由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;
解决方法:
如果您有一个工作副本构造函数和析构函数,则可以使用复制/交换轻松实现赋值运算符,而不是所有代码.
#include <algorithm>
//...
queue& queue::operator=(const queue& v)
{
queue temp(v);
std::swap(temp.first, first);
std::swap(temp.last, last);
return *this;
}
基本上所做的就是通过使用复制构造函数进行临时复制.然后,这个成员与临时成员交换出来.然后在最后,临时将被解除分配(析构函数),并带有旧数据.
我知道与您的尝试相比,代码很小,但它解决了评论中其他人指出的所有问题,增加了异常安全性等等.最重要的是,它的工作原理.
但是请记住,你必须有一个工作的,无错误的复制构造函数和析构函数(此外,你的复制构造函数不能使用赋值运算符,遗憾的是许多不知道的程序员都在这里操作).此外,您必须交换所有成员变量,因此如果向队列类添加更多成员变量,则需要为每个新变量添加交换.
见this for information on the copy / swap idiom.
标签:c,assignment-operator,memory-leaks,linked-list 来源: https://codeday.me/bug/20191003/1850311.html