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

Tejas notrealemail at gmail.com
Mon Sep 20 14:22:18 UTC 2021


On Monday, 20 September 2021 at 14:03:09 UTC, Tejas wrote:
> On Monday, 20 September 2021 at 13:48:01 UTC, Tejas wrote:
>> On Monday, 20 September 2021 at 12:23:00 UTC, Learner wrote:
>>> [...]
>>
>> I think it *is* being called:
>> ```d
>> import std.stdio;
>>
>> struct S
>> {
>> 	int a;
>> 	this(int param){
>> 		a = param;
>> 	}
>> 	~this()
>> 	{
>> 	    writeln("S(",a,") is being destructed");
>> 	}
>> }
>>
>> void main()
>> {
>> 	S[int] aa;
>>         aa[1] = S(5);
>>         aa.remove(1);
>>         aa[1] = S(10);
>>         //writeln("Why no dtor call on remove?");
>> }
>>
>> Output:
>> S(5) is being destructed
>> S(10) is being destructed
>> ```
>> If  the destructors were being executed based on the ending of 
>> scope, `S(10)` would have been destroyed first.
>
> Oh dear, I made a mistake :(
> Sorry, shouldn't have commented out the `writeln`

To make up for my mistake:

In case you still want to delete stuff deterministically despite 
what Steve said, I suggest you make your `struct` a reference and 
use `core.memory.__delete`(not recommended to use this 
carelessly, btw)
```d
import std.stdio;
import core.memory:__delete;

struct S
{
	int a;
	this(int param){
		a = param;
	}
	~this()
	{
	    writeln("S(",a,") is being destructed");
	}
}

void absoluteRemove(AA, keyType)(AA assArray, keyType key){
	__delete(assArray[key]);
}


void main()
{
	S*[int] aa;
         aa[1]  = new S(5);
         absoluteRemove(aa, 1);
         aa[2] = new S(10);
         absoluteRemove(aa, 2);
         writeln("Why no dtor call on remove?");
}
Output:
S(5) is being destructed
S(10) is being destructed
Why no dtor call on remove?
```

Because `__delete` cannot work on stack allocated objects


More information about the Digitalmars-d-learn mailing list