链接列表复制构造函数崩溃程序

时间:2017-02-25 05:10:31

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

我不确定为什么我的拷贝构造函数似乎崩溃了程序,所有其他函数在链表类中都很好。 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

1 个答案:

答案 0 :(得分:2)

仔细研究这三条线:

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

指针current正在使用其他DNode类中的列表。但是back_是当前未初始化的类的成员(它是this->back_),因此具有不确定的值。这将导致未定义的行为

我确定你的意思是rhs.back_

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