Re: side effects on object destruction

From: Markus Mottl (
Date: Sun Jan 17 1999 - 14:22:15 MET

From: Markus Mottl <>
Message-Id: <>
Subject: Re: side effects on object destruction
To: (Xavier Leroy)
Date: Sun, 17 Jan 1999 14:22:15 +0100 (MET)
In-Reply-To: <> from "Xavier Leroy" at Jan 17, 99 11:57:21 am

> > I would like to know whether it is already somehow possible to yield
> > side effects when an object ceases to exist. There is nothing about
> > destructors in the OCAML-documentation. This would allow e.g. closing
> > of open channels or other measures for "cleaning up".
> No, Caml doesn't have destructors or finalization methods a la C++ or
> Java.

What a pity! Would be elegant...

> However, the garbage collector supports the notion of finalized heap
> blocks, which contain a C function that is called when the block is
> freed. This can be used in a C/Caml interface to e.g. deallocate
> system resources.

I try to minimize dependence on anything outside the language / standard
libraries - especially dependence on C code ;-)
Thus, this solution unfortunately does not really appeal to me.


> Sometimes, weak pointers (see the standard library module Weak) can
> also be used to achieve similar effects. For instance, they allow a
> class to keep a hashtable of all objects it has created, while not
> preventing their deallocation when they become unreachable otherwise.

I have not yet thought about this - sounds interesting.

A look at module Weak reveals that one can only create whole arrays
of weak pointers with it - not single instances of weak pointers. This
forces one to think quite a lot about memory management: initial size of
arrays, how to eliminate "dead" pointers from them without leaving holes
(maybe replacing it with the last element and checking this one would do),
what to do if the length of the array does not suffice, etc...

Then, it would be necessary to have an array for each type of object -
hm, maybe every object to be finalized could be subtype of a common class.
This might allow to have just one array.

Every time a new object is created, a weak pointer can be added to
the array and a finalizing function to another array at the same index
position. Before that happens, one could sweep through the array of weak
pointers, eliminate "dead" pointers and call the appropriate finalizing
functions in the other array.

Finally, the "cleanup"-function should be registered with "at_exit".


Uff, seems to be a lot of work to do it right and there are probably lots
of additional things to consider! And efficiency will not be so good -
all this checking for "dead" pointers costs time and would actually not
be necessary if the garbage collector called finalizing functions in
objects... (feature wish intended :-)

Best regards,
Markus Mottl

Markus Mottl,,

This archive was generated by hypermail 2b29 : Sun Jan 02 2000 - 11:58:18 MET