-1

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

1 回答 1

2

仔细看看这三行:

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

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

我确定你的意思是rhs.back_相反。

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

于 2017-02-25T05:17:32.847 回答