简体   繁体   English

Swift中的双重链表:为什么只有一个引用声明为弱?

[英]Doubly linked list in Swift: why is only one of the references declared weak?

class DoublyLLNode<T>{

var value<T>?
weak var prev: DoublyLLNode? = nil
var next: DoublyLLNode? = nil

}

Why is one value, either prev or next, marked weak ? 为什么一个价值,无论是上一个还是下一个,都显得weak Can't we make both as weak? 我们难道不能让两者都变弱吗? If yes, why? 如果是,为什么? If no explain. 如果没有解释。

If both are weak there won't be any strong references to any of the nodes and all of the nodes will be deallocated. 如果两者都很弱,则不会对任何节点进行任何强引用,并且将释放所有节点。

When there is a parent/child relationship you typically have a strong reference to a child in the parent and the child has a weak reference to its parent. 当存在父/子关系时,您通常对父项中的子项具有强引用,并且子项对其父项具有弱引用。 Think of next as the "child" and prev as the "parent". 想想next的“孩子”和prev “父”。

If both are strong you end up with reference cycles. 如果两者都很强,那么最终会有参考周期。

When you have a weak reference to an object, that object can be deallocated at any time, including while you still hold the weak reference to it. 如果对对象有weak引用,则可以随时取消分配该对象,包括在仍然保持对它的弱引用时。 When you have a strong reference to an object, that object will not be deallocated until the strong reference goes away. 如果对对象有strong引用,则在强引用消失之前,不会释放该对象。

Thus, if all of your items in a linked list only have weak references to each other, they can all be deallocated while you're using them since there is no strong reference to any of the items. 因此,如果链接列表中的所有项目仅具有彼此的弱引用,则在您使用它们时可以全部取消分配,因为没有对任何项目的强引用。

You also can't make both references strong. 你也不能使两个引用都很强大。 You will create something called a strong reference cycle. 您将创建一个称为强引用循环的东西。 This is when two objects refer to each other with strong references. 这是两个对象通过强引用相互引用的时候。 Thus, it is impossible for either of the two objects to ever be deallocated (since they reference each other) and you waste memory. 因此,两个对象中的任何一个都不可能被释放(因为它们相互引用)并且你浪费了记忆。

In a linked list node, you want one of the references (either the next or the prev reference) to be strong. 在链表节点,你想引用(或者是一个nextprev参考)要坚强。 Then every object in the linked list will have a strong reference. 然后链表中的每个对象都有一个强引用。 If the next reference is strong, then for any node x , node x - 1 will have a strong reference to it (and presumably whatever code is using the linked list will have a strong reference to the head). 如果next引用很强,那么对于任何节点x ,节点x - 1将具有对它的强引用(并且可能是使用链接列表的任何代码将具有对头部的强引用)。 If the prev pointer is strong, then for any node x , node x + 1 will have a strong reference to it (and you'll need to somehow make sure that there is a strong reference to the tail... otherwise, the tail will be deallocated, then the node in front of the tail, and on and on until all nodes are gone). 如果prev指针很强,那么对于任何节点x ,节点x + 1将具有对它的强引用(并且你需要以某种方式确保对尾部有强引用...否则,尾部将被释放,然后是尾部前面的节点,并且一直打开直到所有节点都消失了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM