nogc associative array?

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Dec 27 16:19:20 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...
>      }
> }

p.s. what you CAN do, on the other hand, is something like this:

  shared static size_t[id] registry;

  this (int id) {
    ...
    regustry[id] = cast(size_t)cast(void*)this;
  }

  ~this () {
    auto me = (cast(size_t)cast(void*)this) in registry;
    if (me !is null) *me = 0;
  }

of course, you have to check if your object is the registry with the
code like this:

  bool inRegistry (const(Foo) obj) {
    auto me = (cast(size_t)cast(void*)obj) in registry;
    return (me !is null && *me != 0);
  }

and you may consider eventual manual GC on registry by removing all 0
values from it. the easiest way to do this is to create a new AA and
copy all non-zero items to it.

please note that:
1. this code assumes that GC is not compacting (it's true for now, but
can be changed in future).
2. trick with `cast(size_t)cast(void*)` is unsafe: class can override
cast operation. you can use slightly safer and uglier code instead:

  auto ptr = cast(size_t)*(cast(void**)&obj);

let the readers of your code to think a little what multiplication
operation for `cast(size_t)` mean. ;-)
-------------- 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/8b8fdaea/attachment.sig>


More information about the Digitalmars-d-learn mailing list