/*========================================================================== * weakref.d * Written in the D Programming Language (http://www.digitalmars.com/d) */ /*************************************************************************** * * * * * Authors: William V. Baxter III * Date: 21 Jan 2008 * Copyright: (C) 2007 William Baxter */ //=========================================================================== module weakref; class WeakRef(T : Object) { private: size_t cast_ptr_; void unhook(Object o) { debug { writefln("Unhook! [%s]",o); } if (cast(size_t)cast(void*)o == cast_ptr_) { o.notifyUnRegister(&unhook); cast_ptr_ = 0; } } public: this(T tptr) { cast_ptr_ = cast(size_t)cast(void*)tptr; tptr.notifyRegister(&unhook); } ~this() { T p = ptr(); if (p) p.notifyUnRegister(&unhook); } T ptr() { return cast(T)cast(void*)cast_ptr_; } WeakRef dup() { return new WeakRef(ptr()); } } static import std.gc; import std.stdio; unittest { class Something { int value; this(int v) { value = v; } ~this() { writefln("something %d destroyed", value); } string toString() { return "Isn't that something (" ~ std.string.toString(value) ~") !"; } } auto a = new Something(1); auto wa = new WeakRef!(Something)(a); std.gc.fullCollect(); writefln("a = ", a); writefln("wa = ", wa.ptr); assert(a is wa.ptr); delete a; std.gc.fullCollect(); writefln("a = ", a); writefln("wa = ", wa.ptr); assert(wa.ptr is null); } //--- Emacs setup --- // Local Variables: // c-basic-offset: 4 // indent-tabs-mode: nil // End: