If we had the following simple double linked list:
class Node{
//...
Node* next;
Node* previous;
int data;
};
class A{
//...
A(const A&);
~A(); //goes through list and deletes each node
A& operator=(const A&);
Node* begin;
Node* end;
int id;
};
A::A(const A& copyThis)
{
//creates a new list that represnets the same data as copyThis's list
//but is not the same list
//Example for clarification:
//if copyThis represented a list of nodes each containing the values 1-10 respectively
//this constructor would make a new list of nodes each containing the values 1-10
//and make the invoking object's members point to the beginning and end of it
//assume this does not create any memory leaks
}
A& A::operator=(const A& a) //this causes a memory leak
{
A* aCopy = new A(a); //now 'a' and 'this' should represent the same
//values but point to different lists
this->begin = aCopy->begin;
this->end = aCopy->end;
this->id = aCopy->id;
//code here that deletes list that invoking object used to point to
//assume it does correctly and without memory leak
return *this;
}
Lets say we have this function:
void foo()
{
A a1();
//put some data into a1
A a2();
{a2=a1;}
}
My question is why this causes a memory leak since a2
should represent the same list of Node
s that aCopy
does inside of operator=
and when a2
goes out of scope it frees the memory allocated for each Node correctly.
EDIT:
Okay So I just realized minutes after posting this question that maybe creating aCopy
with new
allocates memory for more than just the Node
s it represents and that memory is never freed. Is this correct?
EDIT: I am not asking for a better or correct way to write this code, I am ONLY asking for an explanation as to why this causes a memory leak.