简体   繁体   中英

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 ? 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".

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. When you have a strong reference to an object, that object will not be deallocated until the strong reference goes away.

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. 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). 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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