D doesn't have weak references. So how can I make a associative array of objects without preventing their destruction?

evilrat evilrat666 at gmail.com
Thu May 9 15:19:14 UTC 2024


On Thursday, 9 May 2024 at 00:39:49 UTC, Liam McGillivray wrote:
>
> What's a good way I can achieve what I'm trying to do, using 
> either reference counting or a garbage-collected object?

There is libraries like `automem`[1] that implements refcounting 
and more.
Without showing your code for ref counted struct we can't help 
you.

As for weak references, maybe you could "trick" the GC by using 
the fact that simple types are not scanned, i.e. do something 
like this but I have no idea if this is going to work at all, 
alternatively you can also try using `ubyte[size_t.sizeof]`.

Keep in mind that classes is already references so you don't need 
that extra pointer for classes, can be versioned with template 
specialization.

```d
struct WeakRef(T) {
     private size_t _handle; // same size as a pointer

     this(T* ptr) {
         _handle = cast(size_t) ptr;
     }

     T* getRef() {
         return cast(T*) _handle;
     }

     // do the rest ...
}
```

[1] https://code.dlang.org/packages/automem


More information about the Digitalmars-d-learn mailing list