From: Christoph Date: 2002-06-10T00:58:26+09:00 Subject: Re: SWIG & the New Allocation Framework (Ruby 1.7) "Lyle Johnson" wrote in message news:577M8.18673$rX.3117253@e420r-atl1.usenetserver.com... > > L> It looks like the implementation of Foo#initialize should remain the > > L> same. Is there more to it than that? > > > > If you do this all method call must be protected to be sure that > > #initialize was called. This is what ruby do, for example, with File > > > > pigeon% ruby -e 'a = File.allocate; a.read' > > -e:1:in `read': uninitialized stream (IOError) > > from -e:1 > > Of course you're correct, but is it intended that the user will call > Foo.allocate *directly* (as your example shows)? I was under the impression > that code would continue to call Foo.new, which has the following > consequences: You might want to call allocate to create a special instance of your class - lets say class Tree Leaf = allocate # null-tree class << Leaf def size; 0 end def each; Leaf end # ... end def initialize (data; l,r) # ... end def each (&b) # .. end end Generally you probably don't want to call allocate directly - i.e. you might want to think of allocate as a private class method. Here is semi-legitimate example for (1.7 ruby-mswin). --- class A @created = 0 @finalized = 0 def initialize(data) @data = data end class << A attr_reader :created, :finalized protected attr_writer :created, :finalized private def inherited(sub_klass) sub_klass.created = 0 sub_klass.finalized = 0 end def A.allocate @created+=1 obj = super ObjectSpace.define_finalizer(obj,finalizer()) obj end def finalizer proc { |id| @finalized+=1 } end end end class B < A def initialize end end A.new(1) # won't be collected until the end Array.new (10**1) {B.new} proc {A.new(2)}.call p [B.finalized,B.created, A.finalized,A.created] GC.start p [B.finalized,B.created, A.finalized,A.created] # resulting in # [0, 10, 0, 2] # [10, 10, 1, 2] --- /Christoph