crystal icon indicating copy to clipboard operation
crystal copied to clipboard

Fix WeakRef example by removing ref.value call.

Open hugopl opened this issue 4 years ago • 3 comments

The ref.value call cause the GC to not collect ref until end of scope.

Fixes part of https://github.com/crystal-lang/crystal/issues/10469

hugopl avatar Jun 24 '21 00:06 hugopl

I'm not sure if altering the documentation to make it fit is the right way. As far as I understand it, the example should actually be correct. It's wrong that it doesn't work.

At least we should document how to use WeakRef#value (it appears to work if it's used in a different scope as per https://github.com/crystal-lang/crystal/issues/10469#issuecomment-795067583).

straight-shoota avatar Jun 24 '21 08:06 straight-shoota

Yes, it works if in a different scope like

require "weak_ref"
def foo 
  ref = WeakRef.new("oof".reverse)
  p ref.value # => "foo"
  ref
end
ref = foo
GC.collect
p ref.value # => nil

If some day it worked the way the example shows we can consider #10469 a code bug, otherwise it just need doc clarifications.

However I don't know if somebody will be in the mood to do this archaeology and check how it worked years ago.

hugopl avatar Jun 25 '21 04:06 hugopl

I don't mind changing the documentation to reflect the actual behaviour, if we can't fix it immediately. But we're not done with that.

People will expect the current example code to work. #10469 should actually be fixed. Short term, the API should have a note that it does not work like that (for now) and explain the workaround, extracting to a different scope.

straight-shoota avatar Jun 25 '21 09:06 straight-shoota