Object pointers

Bert Freudenberg bert at isg.cs.uni-magdeburg.de
Sat Mar 23 15:52:21 UTC 2002


On Fri, 22 Mar 2002, Chris Becker wrote:

> Basically, I'm trying to create relationships between objects using
> Association. But I became alarmed today when I did the following:
> 
> assoc := Association new.
> 
> aKey := 'keystring'.
> aValue := 'valuestring'.
> 
> assoc key: aKey value: aValue.
> 
> aValue := 'new value'.
> 
> assoc value  ==>  'valuestring'
> 
> This made me think that the association was storing a *copy* of aValue in
> its own instance.

No, it's storing a *reference* to 'valuestring'.  In current Squeak, the
only objects stored as value are SmallIntegers.
 
> Exactly what is going on in this situation?

You create an instance of class Association and store a ref in assoc.
You store a ref to the object 'keystring' in aKey.
You store a ref to the object 'valuestring' in aValue.
You also store a ref to both in the key and value field of assoc.
Then you store a ref to the object 'new value' in aValue.
Since nothing else changes, assoc's value field still points to 'valuestring'.

I always loved the analogy of balloons (objects) held by threads
(references) attached to pins (variables). Balloons (objects) can have
pins (instance variables) by themselves. Balloons can be attached to
multiple pins at the same time (objects can be referenced by more than one
variables), but one pin (variable) only ever holds one balloon (object).  
Attaching a new balloon to a pin (assigning to a variable) cuts the thread
to the balloon previously held there. If the last thread to a balloon is
cut (the last reference is overwritten with another value) the balloon
floats up into the sky and after a while, it gets recycled by a small
plane sweeping the area (unreferenced objects are cleaned up by the
garbage collector, but not immediately). This even works for a network of
balloons (objects referencing each other): Once the last thread to a bunch
of balloons is cut, up it goes.

-- Bert




More information about the Squeak-dev mailing list