[英]Memory leak in my copy constructor for a linked list C++
我正在嘗試為我的類“ IntList”實現一個復制構造函數,但是我不斷收到內存泄漏錯誤,並且難以識別它!
這是我的復制構造函數的實現!
IntList::IntList(const IntList& source) {
Node *y = source.first;
first = new Node;
Node *x = first;
while(y->next != nullptr){
x->info = y->info;
x -> next = new Node;
x = x->next;
y = y->next;
}
x->next = nullptr;
x->info = y->info;
}
這是墨水清單類!
class IntList {
public:
// ctor and 3 methods already done in intlist.cpp:
IntList(); // constructor
void append(int value); // append value at end of list
void print() const; // print values separate by ' '
int count() const; // return count of values
// dtor, copy ctor and 6 other METHODS YOU MUST
// IMPLEMENT IN intlist.cpp:
~IntList(); // destructor
IntList(const IntList& source); //copy constructor (deep copy)
int sum() const; // sum of all values
bool contains(int value) const; // true if value in list
int max() const; // maximum value
double average() const; // average of all values
void insertFirst(int value); // insert new first value
IntList& operator=(const IntList& source); //overloaded
private:
// definition of Node structure (DO NOT CHANGE):
struct Node {
int info;
Node *next;
};
Node *first; // pointer to first node
};
您的析構函數需要遍歷列表並delete
所有new
的節點
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.