So when might you want a WeakRef instead of merely assigning the object to another variable?
The most common use is to prevent a circular references, that is, an object that holds a second object where the second object holds the first object. With a circular reference, you can lose access to an object that will never be destroyed and create a memory leak.
The most common scenario here is the parent/child relationship. Lets say you create a Tree class that can hold many Leaf classes in an array. From any Leaf, you want to be able to get back to its Tree. That is, the Tree is the parent and the many Leaf's are its children. Consider this simple example where a Tree has a single Leaf:
dim t as new Tree dim l as new Leaf t.Child = l l.Parent = t t = Nil l = Nil
Even though we've set both variables to Nil, both still exist because each refers to the other. To prevent that, you'd have to change the code that gets rid of the objects to something like this instead:
t.Child = Nil t = Nil // The Tree object sill exists because l.Parent refers to it l = Nil // No more references to the Leaf, and since it's gone, no more to the Tree either
But there is an easier way. Instead of defining Leaf.Parent as a Tree, define it as a WeakRef instead.
dim t as new Tree dim l as new Leaf t.Child = l l.Parent = new WeakRef( t ) l = Nil // The Leaf still exists because t.Child refers to it t = Nil // Since t was the only reference, Tree goes away and takes Leaf with it
A Computed Property in Leaf that handles the WeakRef mechanics makes the process painless. But either way, since the only "true" reference is of the Parent to its Child, the problem of the Circular Reference evaporates.
In the next post, I'll offer a different example.