On Mon, 18 Oct 2004 18:11:59 +0900, nobu.nokada wrote:

[...]
>> 2) At least in irb, calling define_finalizer within a class, and passing
>> it self as the first arg, causes nothing to happen.  Is define_finalizer
>> the proper way to do this sort of thing, or is there a better way?  Note
>> that I don't want to use Data_Make_Struct's free callback, as I need this
>> to be overridable by users of the class.
> 
> Do you mean like this?
> 
>   ObjectSpace.define_finalizer(self) do |id|
>     # ...
>   end
> 

I mean like this:
    class Foo
        include ObjectSpace
        def initialize
            define_finalizer(self, proc { |a| puts 'inside Foo' })
        end
    end

It seems like it needs to be outside of the class, for some reason.  The
following works:
    x = Foo.new
    include ObjectSpace
    define_finalizer(x, proc { |a| puts 'outside Foo' })

I'm trying to understand why the finalizer defined in the constructor
never gets called.  


> If so, the object is referred as self from the finalizer
so that it
> never get freed.
> 

In both my examples above, the object is referred to by the finalizer; I
don't see what the difference is, from the GC's perspective (assuming it
is the GC that's keeping the finalizer from being called).


> Since not sure what you want really, I cannot tell what is
> "better".  At least, finalizers are different from destructors.

Different how?  Conceptually (according to the pickaxe 1st ed), they
appear to be similar; a method called when the object is destroyed.  The
only difference I can see are scope issues, as apparently
finalizers may not be defined within a class.