2013-03-17 95 views
0

爲什麼ObjectSpace._id2ref在Ruby 1.9和Ruby 2.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" 

回答

1

只是因爲在2.0垃圾收集器是defter。對於

# 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>> 
+0

請參閱我的'EDIT'。使用Ruby2.0輸出更改 – 2013-03-17 08:32:47

+0

您正在嘗試打印出已經清除的內存堆。一切都可能被打印出來,這樣做沒有合同。嘗試至少包含調用'new'和'_id2ref'進入互斥鎖。 – mudasobwa 2013-03-17 08:37:00

+0

你的建議對我很有價值,所以你的建議是什麼,你可以把它寫入你的答案嗎? – 2013-03-17 08:39:56

相關問題