Garbage-collection of objects (Was: [Xotcl] poll for opinions)

Zoran Vasiljevic zoran at archiware.com
Fri Feb 22 11:11:54 CET 2002


Hallo !

The problem of automatic object garbage collection was itching me
for some time now. So I did spend some time and here is the solution.

The basic idea is to auto-destroy objects created within a procedure
when the procedure goes out of context. I would like to hear some
comments from Uwe/Gustaf and/or other experienced XOTcl'ers.
Similar might even be included in 1.0 if people need such thing.
I definitely do.

The below depends on the array "__gc" created in the calling's procedure
context, one class proc "__gc" and one new costructor, "volatile" 
as shown below.

Attached is a piece of test-code to verify the operation.

Cheer's
Zoran

#------- CUT HERE -------

#
# Gets invoked from variable unset callbacks.
#
Class proc __gc {n1 n2 op} {
  set l [::expr {[::info level] > 0}]
  if {![::uplevel $l ::info exists __gc($n1)]} {
      ::incr l
  }
  ::uplevel $l \$__gc($n1) destroy
}

#
# Used to instantiate "volatile" objects. 
# These get auto-destroyed when the procedure goes out of context.
#
Class instproc volatile {n args} {
  ::upvar $n v
  ::trace variable v u [list Class __gc]
  ::set v [[self] autoname -instance [self]]
  ::uplevel [::expr {[::info level]<2?1:2}] ::set __gc($n) $v
  ::eval [self] create $v $args
}

#
# Test routines
#
proc aa {} {
  _foo_ volatile obj
  $obj test
  bb
}
proc bb {} {
  _foo_ volatile obj 
  $obj test
  cc
}
proc cc {} {
  _foo_ volatile obj
  $obj test
  unset obj
  dd
}
proc dd {} {
  _foo_ volatile obj
  $obj test
}
proc gctest {} {
  Class _foo_
  _foo_ instproc test {} {puts stderr [self]}
  set cmds [info comm _foo_*]
  aa
  if {[info comm _foo_*] == $cmds} {
     puts stderr ok    
  } else {
     puts stderr fail
  }
}

#------- CUT HERE -------



More information about the Xotcl mailing list