【问题标题】:How does the copy constructor work when a function passes a parameter by value?当函数按值传递参数时,复制构造函数如何工作?
【发布时间】:2013-10-05 03:47:10
【问题描述】:

我一直在研究一个链表,并有一个函数CountListItems() 按值传递列表。将进行复制并调用复制构造函数。

复制构造函数在尝试复制时崩溃。我很困惑,this 在复制构造函数中指向什么?在这种情况下没有调用对象,对吧?

当我运行调试器时,this 的节点数与参数相同,但其所有值都未初始化。

任何删除this 节点的尝试都会导致崩溃。复制构造函数底部的第 (1) 行是我当前的解决方案。即使程序运行,这是否会导致内存泄漏?

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

【问题讨论】:

  • 注意:在LinkedList 中声明Node 子类后缺少一个分号。而DataInsert 没有返回类型,这是符合标准的 C++ 所必需的。您应该修复both,或发布真实代码

标签: c++ function constructor copy this


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

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

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

  4. 你正在调用InsertData(),你的类中的函数读取DataInsert()。这是错字吗?

【讨论】:

    猜你喜欢
    • 2021-04-05
    • 2018-10-31
    • 2012-01-17
    • 2018-09-23
    • 2012-09-11
    • 1970-01-01
    • 2018-01-20
    • 2016-03-22
    • 2019-01-04
    相关资源
    最近更新 更多