grauzone wrote:
Jarrett Billingsley wrote:
On Sun, Mar 29, 2009 at 4:42 PM, Leandro Lucarella <[email protected]> wrote:
This was discussed several times in the past. For example:
http://www.digitalmars.com/d/archives/digitalmars/D/learn/weak_references_13301.html http://www.digitalmars.com/d/archives/digitalmars/D/learn/Soft_weak_references_8264.html http://www.digitalmars.com/d/archives/digitalmars/D/announce/ANN_WeakObjectReference_-_class_to_hold_weak_references_9103.html
etc.

I hope it helps.

The one provided by Bill:

http://www.dsource.org/projects/scrapple/browser/trunk/weakref

seems to work fine, and has the advantage of working in both Phobos and Tango.

First, I doubt this actually works. The WeakRef stores the pointer as size_t, but the GC is conservative and will still recognize the size_t as a pointer. The unittest in the existing code only works, because he uses an explicit delete on the referenced object.

If the WeakRef is on the stack, this is true.

If the WeakRef is part of an aggregate type that contains pointers, this is true.

Otherwise, the GC will see that the relevant block is marked as having no pointers.

To actually hide the pointer from the GC, you could XOR the size_t value with a constant. Note that you need to be very careful with the WeakRef.ptr() function: what happens, if the GC invalidates the object, and then the user calls ptr() in parallel, before the GC calls rt_detachDisposeEvent()? The user will get an invalid pointer. As far as I remember, rt_detachDisposeEvent() is supposed to be called when all threads have been resumed (after a collect() run). This is to avoid deadlocks if the dispose handler locks something.

True -- weakref is a difficult thing to make thread-safe.

Reply via email to