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

Dukc ajieskola at gmail.com
Fri May 10 11:05:28 UTC 2024


evilrat kirjoitti 9.5.2024 klo 18.19:
> ```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

There is a hidden danger with using this struct. Since `getRef` is a 
template, it will be inferred as `pure`. Now, consider a function using it:

```D
auto derefer(WeakrefT)(WeakrefT wr) => *wr.getRef;
```

This also gets inferred as `pure` - meaning that if you use it twice for 
the same `WeakRef`, the compiler may reuse the result of the first 
dereference for the second call, without checking whether the referred 
value has changed!

You probably should add some never-executed dummy operation to `getRef` 
that prevents it from becoming `pure` if you go with this design.


More information about the Digitalmars-d-learn mailing list