Destroying Objects

Director utilises a system called 'reference counting' - so long as there is at least one reference to an object, that object is kept alive and in memory. When there are no references to an object, the object is marked for deletion in a process called 'garbage collection'.

You can store references to objects in variables (local and even global if you choose), as well as properties of other objects. For example

x = script("test2").new()

put x

-- <offspring "test2" 2 6fbc4e0>"

In this example, a new instance of script("test2") is created and a reference to this object is stored in the variable x. Whilst x still has a reference to the object, the object will stay alive. If we set x to another value (such as VOID), then the object would be de-referenced and destroyed.

It is possible (and quite common) to have more than one reference to an object. For example:

x = script("test2").new()

put x

-- <offspring "test2" 2 6fbc4e0>"

y = x

put x

-- <offspring "test2" 3 6fbc4e0>"

In this example, another reference to the object has been created and stored in the variable y. When we did this, the 'reference count' of the object increased by one. If you look at description of the object that is put to the message window, you will see the number just after the script name increase by one (from 2 to 3). This number indicates the number of current references to the object (one is stored in x, the second is in y and the third is created temporarily when we 'put' the object into the message window. If we were to remove one of these references, the reference count would decrease by one:

put y

-- "

x = "something else"

put y

-- "

In this example, we have removed the original reference that was put into x. The object remains alive because y still has a reference to it, by the reference count decreases.

Self-references and memory leaks.

One flaw of the reference counting system is that it is possible to create self-references that keep objects alive even after all visible references have been destroyed. For example, if you have a script like this

property refToThisObject



on new (me)

  me.refToThisObject =me

  return  me

end

Now, if you created an instance of this object like this...

x = script("test3").new()

put x

-- <offspring "test3" 3 82038d0>

put x. refToThisObject

-- <offspring "test3" 3 82038d0>

you can see that there are 3 references to the object (one is in x, another in the property refToThisObject, and the third is the temporary one). If you removed the reference in x, the object would stay in memory because there is still a reference to the object stored within the object itself - but we would have no way of accessing the object to clear the reference.

First published 02/08/2005