提问人:bb13 提问时间:2/25/2017 最后编辑:J. Piquardbb13 更新时间:2/25/2017 访问量:81
链表复制构造函数崩溃程序 [已关闭]
Linked List copy constructor crashing program [closed]
问:
我不确定为什么我的复制构造函数似乎使程序崩溃,链表类中的所有其他函数都很好。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
答:
2赞
Some programmer dude
2/25/2017
#1
Taking a closer look at these three lines:
const Node* current = rhs.front_;
...
if (current != back_)
...
while (current != back_)
The pointer is using the list from the other class. But is the member of the currently uninitialized class (it is ), and will therefore have an indeterminate value. This will lead to undefined behaviorcurrent
DNode
back_
this->back_
I'm sure you mean instead.rhs.back_
There are also many other problems in how you copy the other list, like for example you never actually initializing in the copy-constructor.back_
评论
0赞
WhozCraig
2/25/2017
@bb13 That would coincide with the whole, "There are also many other problems in how you copy the other list...". It's time to break into your debugger and start single-stepping.
评论
nullptr
DList(const DList& rhs) : back_(nullptr), front_(nullptr), listSz(0) { ... }
.