这是
this question的一个想法:在创建对象时,增加一个类变量.当对象被收集时,减少它.如您所见,调用终结器,并且@@ no_foo减少.但是当我稍后查询它时,减量就消失了.似乎价值只会上升,永不下降(如果我创建两个对象,它将显示2).我错过了一些明显的东西吗
class Foo @@no_foo = 0 def initialize puts 'creating object' @@no_foo += 1 ObjectSpace.define_finalizer(self,proc { self.delete }) end def delete puts 'deleting object' @@no_foo # => 1 @@no_foo -= 1 @@no_foo # => 0 end def self.no_foo @@no_foo # => 0,1 end end Foo.no_foo # => 0 f = Foo.new f = nil GC.start Foo.no_foo # => 1 # >> creating object # >> deleting object
解决方法
它可以工作,但在最终确定中有循环引用.您的终结器取决于应该收集的对象的绑定.见
this solution.
class Foo @@no_foo = 0 def initialize @@no_foo += 1 ObjectSpace.define_finalizer(self,Foo.method(:delete)) end def self.delete id # also this argument seems to be necessary @@no_foo -= 1 end def self.no_foo @@no_foo end end Foo.no_foo # => 0 1000.times{Foo.new} Foo.no_foo # => 1000 GC.start Foo.no_foo # => 0