On Sat, 27 Dec 2014 23:43:54 +0000 aldanor via Digitalmars-d-learn <[email protected]> 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. ;-)
signature.asc
Description: PGP signature
