Weak references

Reference counting has one fatal flaw, which is the reason why it's not used by default for all variables in every programming language: cycles. If two or more reference counted values somehow refer to each other, their lifetimes would never end. They form what is called a cycle.

It isn't always obvious when a cycle happens. If A refers to B, which refers to C, which refers to D, which refers to A, we still have a cycle.

We can break cycles by using weak references, which are an ancillary data type for Rc. When we have an Rc, we can call its downgrade function (for example, let weak_mel = Rc::downgrade(&mel)) to retrieve a Weak data value.

We can't actually do anything with a Weak except retrieve an Rc by calling its upgrade function (for example weak_mel.upgrade()), but using a Weak lets us keep track of a reference-counted value without actually referencing it, which means we can avoid creating cycles while still organizing our information in the way that seems natural.

If the number of Rcs that reference a data value is zero, that data value's lifetime ends, even if there are still Weaks that reference the value.

Because the referenced value might not exist anymore, the upgrade function returns an Option. When we call upgrade, we'll either get a Some containing our Rc, or we'll get None.

So, the pattern here is that we use Rc when we want to make sure that the data value sticks around as long as we need it, and Weak when we know it's going to stick around (for example, when it's referring to the parent node in a tree structure) or when we don't care whether it sticks around (for example, when it's a cached value that we can regenerate if it's missing).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.41.229