0

为什么ObjectSpace._id2ref在 Ruby 1.9 和 Ruby 2.0 上给出不同的输出?

红宝石 1.9.3p392 i386-mingw32

class Foo ; end

Foo.object_id                     #=> 17569464
ObjectSpace._id2ref(17569464)     #=> Foo

Foo.new.singleton_class.object_id #=> 17075124
ObjectSpace._id2ref(17075124)     #=> "\x00"

红宝石 2.0.0p0 i386-mingw32

class Foo ; end

Foo.object_id                     #=> 17197176
ObjectSpace._id2ref(17197176)     #=> Foo

Foo.new.singleton_class.object_id #=> 19181436
ObjectSpace._id2ref(19181436)     #=> RangeError: 0x124af7c is recycled object

Foo.new.singleton_class.object_id #=> 17454324
ObjectSpace._id2ref(17454324)     #=> RangeError: 0x10a54f4 is not id value

Foo.new.singleton_class.object_id #=> 17139816
ObjectSpace._id2ref(17139816)     #=> "c"
4

1 回答 1

1

只是因为在2.0垃圾收集器中比较灵巧。

# RangeError: 0x124af7c is recycled object

对象的状态已经被 GC'ed

UPD:我们可以通过以下方式处理请求的行为Mutex

2.0.0 (main):0 > Mutex.new.synchronize {
2.0.0 (main):0 *   class Foo ; end
2.0.0 (main):0 *   id = Foo.new.singleton_class.object_id
2.0.0 (main):0 *   puts id
2.0.0 (main):0 *   puts ObjectSpace._id2ref(id)
2.0.0 (main):0 * }  
# 23172260
# <Class:#<Foo:0x00000002c32970>>
于 2013-03-17T08:24:40.703 回答