0

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;
}
4

1 回答 1

1
  1. 您刚刚声明了destructorlike ~LinkedList();。理想情况下,您也应该定义它,并且应该delete在其中编写一些代码以释放一些内存。或将定义留空为~LinkedList() { }。这就是(2)产生崩溃的原因。

  2. 您应该有一种default constructor或其他方式来初始化指针。如果在未初始化的情况下使用指针,则缺少此步骤将生成异常。

  3. 正如 WhozCraig 在评论中已经提到的那样,struct定义应该以;- 分号结尾。

  4. 您正在调用InsertData()并且您的类中的函数读取DataInsert(). 这是一个错字吗?

于 2013-10-05T04:09:53.280 回答