D doesn't have weak references. So how can I make a associative array of objects without preventing their destruction?
Steven Schveighoffer
schveiguy at gmail.com
Thu May 9 15:34:57 UTC 2024
On Thursday, 9 May 2024 at 00:39:49 UTC, Liam McGillivray wrote:
> A "weak reference" (in the sense that I'm referring to) is a
> feature in some programming languages for a reference to an
> object that doesn't prevent the GC from destroying that object.
>
> My current understanding is that D doesn't have weak
> references, though I've found some posts in this forum from
> many years back that mention something called "weakref". So is
> weakref a real thing, or just a concept that never got
> implemented?
>
No, D does not have any built-in support for weak references.
> What's a good way I can achieve what I'm trying to do, using
> either reference counting or a garbage-collected object?
In order to have weak references, they have to be invalidated
when the item itself is destroyed. I think the most logical
mechanism is to have a registry of weak reference ids, and you
point at that. Then the item itself, when destroyed, goes and
updates the weak reference registry with a null pointer so the
weak references when looking up the value get a null pointer.
The registry needs to outlive all other weak references, and the
things that its pointing to. This means probably either reference
counting or some global structure that is never deleted. The key
thing is that the registry cannot be collected before the things
that use it.
-Steve
More information about the Digitalmars-d-learn
mailing list