Why dtor are not executed when removing a struct from associative arrays?

Steven Schveighoffer schveiguy at gmail.com
Mon Sep 20 13:57:18 UTC 2021


On 9/20/21 8:23 AM, 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

AA values are not destroyed on removal. For a simple reason -- someone 
might still be referencing it.

```d
struct S
{
    int x;
}
void main()
{
    S[int] aa;
    aa[1] = S(5);
    auto sptr = 1 in aa;
    sptr.x = 6;
    assert(aa[1].x == 6);
    aa.remove(1);
    assert(sptr.x == 6;
}
```

-Steve


More information about the Digitalmars-d-learn mailing list