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

bauss jj_1337 at live.dk
Fri Dec 22 05:03:38 UTC 2017


On Thursday, 21 December 2017 at 19:43:16 UTC, Steven 
Schveighoffer wrote:
> On 12/20/17 9:57 PM, Mike Franklin wrote:
>> [...]
>
> 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

Except for that in C# you have the IDisposable interface, which 
can actually be used to prevent this kind of stuff and generally 
used to clean up non-GC memory.


More information about the Digitalmars-d-learn mailing list