Why dtor are not executed when removing a struct from associative arrays?
jfondren
julian.fondren at gmail.com
Mon Sep 20 13:51:00 UTC 2021
On Monday, 20 September 2021 at 12:23:00 UTC, Learner wrote:
> I was expecting something like going out of scope for that
>
> ```(D)
> import std.stdio;
>
> struct S
> {
> ~this()
> {
> writeln("S is being destructed");
> }
> }
>
> void main()
> {
> S[int] aa;
> aa[1] = S();
> aa.remove(1);
> writeln("Why no dtor call on remove?");
> }
>
> I was expecting S instance dtor called
> S is being destructed
> ```
This looks to me like a bug, as
```d
import core.memory : GC;
GC.collect;
```
immediately after the `.remove` will call the struct's destructor.
I only see https://issues.dlang.org/show_bug.cgi?id=20379 as
related, though.
Here's another workaround:
```d
alias purge = (kv, k) { kv[k] = typeof(kv[k]).init; kv.remove(k);
};
```
with the same caveat of the `.init` structs also getting
destructed later, you can use that in place of `.remove`.
More information about the Digitalmars-d-learn
mailing list