digitalmars.D.learn - WeakRef implementation
- Hakan Aras (29/29) Jul 13 2019 Is this implementation of WeakRef correct? Is it portable? I
Is this implementation of WeakRef correct? Is it portable? I tested it and it seems to work, but I'm not real familiar with the runtime or the GC. Also is there any way to convert this into a struct instead of class? (Not possible this way due to frame pointer for onDispose) extern (C) void rt_attachDisposeEvent(Object, void delegate(Object)); extern (C) void rt_detachDisposeEvent(Object, void delegate(Object)); class WeakRef(T) if (is(T == class)) { this(T element) { address = *cast(size_t*)&element - offset; rt_attachDisposeEvent(element, &onDispose); } private extern (C) void onDispose(Object _) { assert(_ is element); address = 0 - offset; } alias element this; inout(T) element() inout { size_t result = address + offset; return *cast(typeof(return)*)&result; } private static immutable size_t offset = 16_785_407; private size_t address; } auto weakRef(T)(T element) { return new WeakRef!T(element); }
Jul 13 2019