[英]C++ linked List assignment Operator
嘗試為單個鏈表類構建賦值運算符。 我以為我正確構建了它,但仍然出現內存泄漏。
該類由 First 和 Last 變量組成。 然后是一個 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;
如果您有工作復制構造函數和析構函數,則可以使用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;
}
基本上所有所做的都是通過使用復制構造函數制作的臨時副本。 隨后的成員(們) this
與臨時成員交換出去。 然后最后,臨時數據將被釋放(析構函數),連同舊數據一起。
我知道與您的嘗試相比,代碼很小,但它解決了其他人在評論中指出的所有問題,增加了異常安全等。最重要的是,它有效。
但請記住,您必須有一個有效的、無錯誤的復制構造函數和析構函數(此外,您的復制構造函數不得使用賦值運算符,不幸的是,許多不知情的程序員都在這樣做)。 此外,您必須交換所有成員變量,因此如果向queue
類添加更多成員變量,則需要為每個新變量添加一個swap
。
有關復制/交換習語的信息,請參見此處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.