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