On 9/20/21 5:23 AM, Learner wrote:

I was expecting S instance dtor called
S is being destructed

If you are sure the element can be destroyed, you can call destroy():

import std.stdio;

enum someSpecialInitValue = 777;

struct S
{
  int i = someSpecialInitValue;

  this(int i)
  {
    this.i = i;
  }

  ~this()
  {
    writeln("S with ", i, " is being destructed");
  }
}

void destroyAndRemove(AA, Key)(AA aa, Key key) {
  auto found = key in aa;
  if (found) {
    destroy(*found);
    aa.remove(key);
  }
}

void main()
{
  S[int] aa;
  aa[1] = S(1);
  aa.destroyAndRemove(1);
  writeln("Actually, 2 dtor calls! :)");
}

destroy() puts the object to its initial state, which means, it gets destroyed again. That's why there are two destructor calls below for the same object. I used a special value to demonstrate the second destructor is called on the init state:

S with 1 is being destructed
Actually, 2 dtor calls! :)
S with 777 is being destructed

Ali

Reply via email to