Don't expect class destructors to be called at all by the GC
Steven Schveighoffer
schveiguy at yahoo.com
Thu Dec 21 19:43:16 UTC 2017
On 12/20/17 9:57 PM, Mike Franklin wrote:
> "Don't expect class destructors to be called at all by the GC"
>
> I was a bit shocked to read that here:
> https://p0nce.github.io/d-idioms/#The-trouble-with-class-destructors
>
> The document tries to clarify with:
> "The garbage collector is not guaranteed to run the destructors for all
> unreferenced objects."
>
> Unfortunately, that doesn't really shed much light on this oddity. So,
> specifically, under what circumstances are destructors not called?
It's implementation defined :)
The gist is, you cannot expect that destructors will be run in a timely
manner, or at all.
They may be called, and most of the time they are. But the language nor
the current implementation makes a guarantee that they will be called.
For this reason, any classes that use non-memory resources should clean
up those resources before becoming garbage. This is why most of the
time, such items are managed by structs.
Note that the same non-guarantee exists in other GC'd languages, such as
Java or C#.
-Steve
More information about the Digitalmars-d-learn
mailing list