[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Remi VANICAT <vanicat@l...> |
| Subject: | Re: [Caml-list] initializers and destructor |
Stefano Zacchiroli <zack@cs.unibo.it> writes:
> Hi all,
> I know and frequently use "initializer" construct in classes, but I'm
> not able to find something like destructor that works exectly like an
> initializer but that is invoked just before an object last reference is
> lost.
>
> Is this somewhat difficult to implement in relation with the OCaml GC or
> I'm simply missing something?
there is the finalise function in the module Gc of the standard
library.
one can write a destructor using it :
# class foo =
let f x = print_string "test"; print_newline () in
object(s)
initializer
Gc.finalise f s
end;;
class foo : object end
# new foo;;
- : foo = <obj>
# Gc.full_major ();;
test
- : unit = ()
#
but you should know that there is some pitfall with finalise :
# class foo =
object(s)
val bar = "test"
initializer
Gc.finalise (fun x -> print_string bar; print_newline ()) s
end;;
class foo : object end
# new foo;;
- : foo = <obj>
# Gc.full_major ();;
- : unit = ()
# Gc.full_major ();;
- : unit = ()
here, the created object is reachable from the closure of
finalisation, so it's reachable, and never garbage collected.
You should carefully read it's documentation
--
Rémi Vanicat
vanicat@labri.u-bordeaux.fr
http://dept-info.labri.u-bordeaux.fr/~vanicat
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners