【问题标题】:C++ understanding pointer with copy constructorC++ 用复制构造函数理解指针
【发布时间】:2020-11-13 13:22:20
【问题描述】:

我有一个简单的 LinkedList 类,带有基本操作(添加/删除等)和一个复制构造函数:

LinkedList::LinkedList(const LinkedList& other) {
    data_ = other.data_;
    if (other.next_ == nullptr) next_ = nullptr;
    else next_ = new LinkedList(*other.next_);
}

我认为以下行为是预期的,但我不确定为什么......

int main() {
    LinkedList list1;
    list1.insert(1);
    list1.insert(2);

    // prints 1->2
    list1.print();

    // Copy constructor called
    LinkedList list2(list1);

    list1.insert(3);
    // prints 1->2->3
    list1.print();

    // prints 1->2
    list2.print();

    // Memory addresses are different
    cout << &list1 << " " << &list2 << endl;

    delete &list1;
    
    // Nothing printed
    list2.print();

}

list1被删除的时候是不是也要删除list2的引用?

【问题讨论】:

  • delete &amp;list1; 是非法的,因为你没有(也不应该)LinkedList* list1 = new LinkedList;

标签: c++ copy-constructor deep-copy


【解决方案1】:

list1 是在自动存储(“堆栈”)中创建的,因此您不能在其地址上调用delete。这样做会导致未定义的行为,这意味着任何事情都可能发生,包括 list2 损坏或程序彻底崩溃。

要测试您的复制构造函数是否正常工作,您可以使用new 在动态存储(“堆”)中创建两个列表,该列表必须与匹配的delete 配对:

int main() {
    LinkedList *list1 = new LinkedList();
    list1->insert(1);
    list1->insert(2);

    // prints 1->2
    list1->print();

    // Copy constructor called
    LinkedList *list2 = new LinkedList(*list1);

    list1->insert(3);
    // prints 1->2->3
    list1->print();

    // prints 1->2
    list2->print();

    // Memory addresses are different
    cout << list1 << " " << list2 << endl;

    delete list1;
    
    // Still prints 1->2
    list2->print();

    delete list2;
}

【讨论】:

  • 感谢您的快速回复和解释!
猜你喜欢
  • 2016-04-13
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 2016-04-08
  • 2011-02-09
相关资源
最近更新 更多