为什么通过分配指针来连接两个链表是错误的? [英] Why is concatenating two linked lists by assigning pointers wrong?

查看:37
本文介绍了为什么通过分配指针来连接两个链表是错误的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我们的讲师只是向我们展示了如何连接两个链表,然后继续向我们展示了示例,如果实施该示例将是错误的,我似乎不太了解为什么它不能很好地工作,因为它没有解释.如果我以这种方式连接两个链表,会出现什么问题:

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;
}

推荐答案

问题中使用的方法是错误的,因为它错误地共享了

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

list 拥有其节点.它维护并最终释放它们.通过将指向 list 所拥有的节点的指针提供给接收链表,您现在将具有两个链表,它们引用并尝试拥有相同的节点集.如果以后修改 list ,则将修改接收器,并可能使其处于不一致状态(例如, end 可能不再正确).如果您稍后销毁 list,则在 list 销毁其节点后,接收器将指向无效内存.同样,通过修改或销毁接收器, list 处于不稳定状态.

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.

这与三个规则有关,这就是复制三项规则所要求的构造函数,我将利用它来摆脱这种混乱局面.我会按值而不是作为参考传递 list ,以便正确地复制它,然后将其节点列表(即源列表所拥有的节点的副本)移动到接收链接列表中.然后,您可以清理 list ,以便安全销毁并在超出范围时使其死亡.这种方法可能有点慢,但是几乎是万无一失的.请参阅复制并交换成语,以了解几乎相同的技巧赋值运算符.

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.

这篇关于为什么通过分配指针来连接两个链表是错误的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆