5.6. Object destruction

The lifetime of objects is controlled by the garbage collector within the TOM Runtime. When no remaining strong references to an object remain, the GC will collect the object, deallocating the memory consumed by the object. Just before the GC collects the object, it invokes a deallocation notification method on the object whose default implementation is provided by State:


void
  dealloc
{
  void;
}

An object must override this method to perform cleanup operations specific to the needs and implementation of that object, such as closing files, shutting down database connections, or freeing OS resources. An example of this is Descriptor:


void
  dealloc
{
  if (descriptor != -1)
    bind ((stream-error, nil))
      [self close];
}

This method ensures that the Descriptor is closed, avoiding the leak of a file descriptor at the OS level.

When implementating a dealloc method, care must be taken to avoid messaging any other objects from within this method, as they may have become garbage as well, and already been collected. Since class objects can not become garbage, it is safe to message class objects.

There are no guarantees that an object will be collected in a timely manner, or even at all (should references remain). This makes it critical that garbage collected objects not be relied upon to manage the lifetime of very limited resources such as file descriptors. They should also not be used to manage objects whose collection is time critical, such as objects which are user-visible.