Why is concatenating two linked lists by assigning pointers wrong?

懵懂的女人 提交于 2019-12-13 03:06:10

问题


So our lecturer just showed us how to concatenate two linked list but then went on and showed us and example that would be wrong if implemented,I don't seem to quite understand why it won't work as good,since it wasn't explained.What would be the problem if I concatenate two linked lists this way:

template <typename T>
void LList<T>::concat(LList<T> const & list) {
    end->next = list.start;
    end = list.end;
}

回答1:


The approach used in the question is wrong because it incorrectly shares Ownership of the transferred nodes.

list owns its nodes. It maintains and ultimately releases them. By giving pointers to nodes owned by list to the receiving linked list, you will now have two linked lists referring to and trying to own the same set of nodes. If you later modify list, you will modify the receiver and potentially leave it in an inconsistent state (end may no longer be correct, for example). If you later destroy list, the receiver is left pointing to invalid memory after list destroys its nodes. Likewise list is left in a precarious state by modifying or destroying the receiver.

This is somewhat related to The Rule of Three, and it's the copy constructor required by Rule of Three that I'd take advantage of to get out of this mess. I'd pass list in by value rather than as a reference so that it is correctly duplicated and then move its list of nodes, copies of the nodes owned by the source list, into the receiving linked list. You can then clean up list so that it is safe to destroy and leave it to die when it goes out of scope. This approach may be a little slow, but it's very nearly foolproof. See the Copy and Swap Idiom for a nearly identical trick being applied to the assignment operator.



来源:https://stackoverflow.com/questions/53549520/why-is-concatenating-two-linked-lists-by-assigning-pointers-wrong

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!