I've been working on a linked list and have a function CountListItems()
that passes the list by value. A copy is to be made and the copy constructor is invoked.
The copy constructor crashes when it attempts to make a copy. I'm confused, what does this
point to in the copy constructor? There is no calling object in this case, right?
When I run the debugger, this
has the same number of nodes as the parameter but all of its values are uninitialized.
Any attempt to delete the nodes of this
causes a crash. Line (1) at the bottom in the copy constructor is my current solution. Does this cause a memory leak even though the program works?
//main.cpp
int CountListItems(LinkedList data);
int main ()
{
LinkedList list;
int x = 1;
list.InsertData(x);
/* Pass LinkedList by value, so that the copy constructor is invoked. */
CountListItems(data);
return 0;
}
//LinkedList.h
class LinkedList
{
public:
struct Node
{
int data;
Node *prev;
Node *next;
}
/* Copy constructor */
LinkedList(LinkedList &original);
~LinkedList();
DataInsert(int data);
private:
/* Copy list node by node. */
void CopyList(LinkedList &original);
Node *first;
Node *curr;
Node *last;
};
//LinkedList.cpp
/* Copy Constructor */
LinkedList::LinkedList(LinkedList &original)
{
first = last = curr = 0; // (1) Attempt at a solution (Initialize "this")
/* this->~LinkedList(); */ // (2) Produces Crash
CopyList(original); // (3) Without (1) Produces Crash
return;
}