Don't expect class destructors to be called at all by the GC

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Feb 1 06:54:18 UTC 2018


On Wednesday, January 31, 2018 10:51:10 DanielG via Digitalmars-d-learn 
wrote:
> On Wednesday, 31 January 2018 at 10:34:53 UTC, Mike Parker wrote:
> > delete is deprecated:
> >
> > https://dlang.org/deprecate.html#delete
>
> Ah, thanks! Actually double-thanks, because my progress through
> your book is what prompted me to search for threads about class
> destructors. The existence of .destroy answers my question
> (namely, "should I just use 'delete', or my own .dispose method,
> for deterministic resource freeing?")

The main problem with delete is that it's inherently unsafe. GC-managed
memory is supposed to be @safe (it's one of the main reasons that D has a GC
in the first place), but having the programmer go and delete a GC-managed
object rather than waiting for the GC to do it makes it trivial to do wrong
stuff like free an object's memory while it's still referenced by something
else (the sort of thing that the GC is supposed to avoid). It's far better
to either explicitly destroy the object without freeing its memory or to use
memory that is not managed by the GC if you want deterministic destruction
of an object on the heap.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list