【问题标题】:Linked List copy constructor crashing program链表复制构造函数崩溃程序
【发布时间】:2017-02-25 05:10:31
【问题描述】:

我不确定为什么我的复制构造函数似乎使程序崩溃,所有其他函数在链表类中都很好。 5 规则现在真的让我对实施感到困惑。如果有人对我出错的地方有一些指示或指导,请告诉我,谢谢。

DList ctor:

DList() {
    //Node* front_;
    front_ = new Node(); // creating front sentinel
    //Node* back_;
    back_ = new Node(); // creating back sentinel
    //make them point to eachother
    front_->next_ = back_;
    back_->prev_ = front_;
    listSz = 0;
}

析构函数和复制构造函数:

//destructor
~DList() {

    Node* current = front_;

    while (current != back_)
    {
            front_ = front_->next_;
            delete current;
            current = front_;
    }
}
// copy ctor
DList(const DList& rhs) {
    cout << "in ctor" << endl;
    const Node* current = rhs.front_;
    Node* temp = nullptr;
    if (current != rhs.back_)
    {
        cout << "in if" << endl;
        front_ = new Node(current->data_);
        temp = front_;
        current = current->next_;
    }
    while (current != rhs.back_)
    {
        cout << "in while" << endl;
        Node* nn = new Node(current->data_);
        temp->next_ = nn;
        temp = temp->next_;
        current = current->next_;
    }
    cout << "test";
}

主要:

int main(void) {
    DList<int> list;
    DList<int> list2;
    DList<int>::const_iterator it;

    cout << list.size() << endl;
    list.push_front(1);
    list.push_front(2);
    list2.push_back(3);
    list2.push_front(4);
    list.print();

    std::cout << endl;


    list2.print();

    DList<int> list3 = list;
    list3.print();
}

崩溃前的输出:

0
2
1

4
3
in ctor
in if
in while
in while
test
2
1

【问题讨论】:

  • 您的复制构造函数应该预先在初始化列表中将这些成员指针设置为nullptr
  • 你会怎么做呢?
  • @PaulMcKenzie 将左侧成员设置为空?
  • DList(const DList&amp; rhs) : back_(nullptr), front_(nullptr), listSz(0) { ... }.
  • 现在按预期工作

标签: c++ linked-list copy-constructor doubly-linked-list rule-of-three


【解决方案1】:

仔细看看这三行:

const Node* current = rhs.front_;
...
if (current != back_)
...
while (current != back_)

指针current 正在使用来自另一个DNode 类的列表。但是back_ 是当前未初始化类的成员(它是this-&gt;back_),因此会有一个不确定的值。这将导致未定义的行为

我确定您的意思是 rhs.back_

在如何复制其他列表方面还有许多其他问题,例如,您实际上从未在复制构造函数中初始化 back_

【讨论】:

  • @bb13 这与整体一致,“在如何复制其他列表时还有许多其他问题......”。是时候进入您的调试器并开始单步执行了。
猜你喜欢
  • 2014-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多