Use of finalizers

After months of little activity here, I have a second question for today :slight_smile:

I am trying to use a finalizer for a little cleanup work with some C++
extensions, but I am missing something:
class Foo
def initialize()
puts "Constructed new object… #{self.id}"
ObjectSpace.define_finalizer(self, Proc.new { |id|
puts “Destroying #{id}”
})
end
end

if FILE == $0
foo = Foo.new
foo = nil
GC.start
foo = Foo.new
ObjectSpace.define_finalizer(foo, Proc.new { |id| puts “Outside #{id}”})
foo = nil
GC.start
end

output:

vor-lord:scripts/ruby> ruby Foo.rb
Constructed new object… 537849088
Constructed new object… 537849068
Outside 537849068

So the finalizer isn’t called when it is registered in the constructor (in
fact I’ve tried several ways to define a finalizer for self without
success).

What is the principle that I am breaking?

···


The key of strategy… is not to choose a path that leads to victory, but
to choose so that all paths lead to a victory.
– L.M. Bujold

http://www.rubygarden.org/ruby?DiscussionOnUsingFinalizers
http://www.rubygarden.org/ruby?ObjectsNotGetFinalized
http://www.rubygarden.org/ruby?RubyIdioms

···

On Wed, Sep 11, 2002 at 04:35:27AM +0900, Brett Williams wrote:

After months of little activity here, I have a second question for today :slight_smile:

I am trying to use a finalizer for a little cleanup work with some C++
extensions, but I am missing something: