Forum Navigation
Weak and soft references
Posted: 04/04/09 21:29:36Hello!
It would be great if there was a way to create weak and soft references with Tango. A weak reference is an object-reference that is not taken into account during garbage-collection, and that is set to "null" when the referenced-object is deleted. A soft-reference is the same thing, except the reference is not set to "null" on object-deletion.
These two mechanisms are sometimes necessary if you want to prevent the garbage-collection from not collecting some allocated objects in some cases. For example, here is a code-sample that would require soft-references in order to work properly:
class Window { static LinkedList!(SoftRef!(Window)) s_allWindows; this() { s_allWindows.append(this); } ~this() { s_allWindows.remove(this); } static void showAll() { foreach (window; s_allWindows) window.show(); } }Here, without soft-references, the windows would always be referenced by the static-list and thus would never been garbage-collected.
For the implementation of the weak/soft-reference mechanism, I think it could be based on Bill Baxter's implementation that can be found here: http://www.dsource.org/projects/scrapple/browser/trunk/weakref/weakref.d. It just needs to be fixed by xor'ing the pointer-address by a constant-mask in order to hide the reference from the garbage-collector.
I really think weak and soft references need to be implemented in Tango. Lots of cases need them in order to make the garbage-collection work properly.