Destructor called while object is still alive

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Fri Oct 23 07:32:02 UTC 2020


On Friday, 23 October 2020 at 06:15:32 UTC, frame wrote:
> Not sure if this is expected behaviour, but I find this weird:
> The destructor is called on the object just because it gets out 
> of scope?

The destructor may not be called at all by the GC, or it might be 
called whenever there is no pointer found in memory/registers. 
Since D is essentially using C-style code-gen/optimizers that has 
little to no knowledge of a GC it may be called prematurely or 
never.

So basically, destructors do not play well with GC. I've in the 
past argued that one should not allow destructors on GC objects 
since there are no proper guarantees anyway. That could also 
speed up collection. But people prefer convenience over 
correctness...

IMO, rule of thumb: do not rely on destructors being called at 
the appropriate time for objects on the GC heap. Do explicit 
finalisation instead.




More information about the Digitalmars-d mailing list