[Newbies] What is a "weak" reference

Michael Davies mykdavies+squeak at gmail.com
Mon Jul 14 10:07:51 UTC 2008

On Sun, Jul 13, 2008 at 6:15 PM, Rob Rothwell <r.j.rothwell at gmail.com> wrote:
> Can someone explain what a "weak" vs (I am guessing) "strong" reference is?
> I, too, am maintaining parent/child relationships in my application and have
> just been doing something like:
> Parent>>createChild
>      |child|
>      child := Child new parent: self.
>      ^child
> I am assuming, given my troubles, that this is NOT a weak reference?!

Hi Rob,
Have a look at the class comment on WeakArray: "WeakArray is an array
which holds only weakly on its elements. This means whenever an object
is only referenced by instances of WeakArray it will be garbage

My understanding of this is that garbage collection is done by
reference counting, and so the situation you described may result in
parent and child forming a circular reference to each other, and so
never being collected - but it depends on what you do with that return

I note that there are very few uses of any Weak* classes in the image,
so it's likely that there is a better way of implementing what you're
aiming for; eg the child could drop its direct parent reference, and
do something like

    ^ Parent allInstances detect: [ :each | each children includes: self ]

(or vice versa depending on which way you're more likely to traverse
the relationship).

This is just me thinking out loud though - perhaps someone else could
comment on best practice in this case. "Smalltalk Best Practice
Patterns" is very useful in answering these types of questions, but my
copy is in a box somewhere at the moment.

Hope this helps, Michael

More information about the Beginners mailing list