AA .remove() doesn't destroy a value struct
Consider the following:
struct Noisy { int id; ~this() { import std.stdio : writefln; if (id) writefln!"[#%d] I am being destroyed!"(id); } } void main() { Noisy[int] noises; noises[4] = Noisy(4); auto six = Noisy(6); noises[5] = Noisy(5); noises.remove(4); noises.remove(5); }
You may expect to the output to look like this:
[#4] I am being destroyed! [#5] I am being destroyed! [#6] I am being destroyed!
But in fact, the last line will come first as six
is destroyed at the end of the scope, and the other objects are only destroyed later.
Steven Schveighoffer explains:
AA values are not destroyed on removal. For a simple reason -- someone might still be referencing it.
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; }
As with any struct you can overwrite it instead: noisy[4] = Noisy.init;
, which is pretty much what noisy[4].destroy;
does. Note that neither of these examples remove 4
as a key of the AA.