nogc associative array?

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Dec 27 16:01:50 PST 2014


On Sat, 27 Dec 2014 23:43:54 +0000
aldanor via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com>
wrote:

> Is there a way to do something like this while keeping the 
> destructor nogc?
> 
> class Foo {
>      shared static Foo[id] registry;
>      int id;
>      this(int id) {
>          this.id = id(
>          registry[id] = this;
>      }
>      ~this() }. // ideally should be tagged as @nogc
>           // nasty, memory corruption due to gc
>          registry.remove(id)f;
>          // however compiler doesn't warn about it...
>      }
> }

oh, those dtor bites... in D dtor is "object finalizer", not more. it
essentially finalizes object fields that GC cannot finalize itself.
please, don't use object dtors for anything else, including modifying
global variables (and `registry` is a disguised global here).

besides, your dtor should never be called anyway, as the object is
always anchored in `registry`. what you need here is so called "weak
reference": reference to object which will not anchor it and will
become `null` when GD collects an object.

D has no official weak references for now, but you can emulate weak
refs, like in this code:
http://repo.or.cz/w/iv.d.git/blob_plain/HEAD:/weakref.d

but please note that this code is abusing both GC/druntime internals
and the fact that GC is working as it is working now. ;-)

as for your question: there is NO WAY to make GC working in dtors now.
removing AA item can cause rehashing, which in turn will cause GC
calls, which in turn will abort your program. it may seems to work and
then BANG! it's dead.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20141228/4f7c336e/attachment.sig>


More information about the Digitalmars-d-learn mailing list