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

Mike Parker aldacron at gmail.com
Fri Dec 22 01:23:26 UTC 2017


On Friday, 22 December 2017 at 00:09:31 UTC, Mike Franklin wrote:

>
> What condition(s) would cause a destructor for an object that 
> is managed by the GC to potentially not be called?
>

Here:

===========
import std.stdio;

class Clazz {
     ~this() {
         writeln("Class dest");
     }
}

void makeClazz() {
     auto clazz = new Clazz;
}

void main() {
     makeClazz();
}

static ~this() {
     writeln("Static dest");
}
============

This outputs:

============
Static dest
Class dest
============

The class destructor is not run during the lifetime of the 
program. The fact that it's run during runtime termination is an 
implementation detail. Another implementation might not run a 
finalization at termination.

So the destructors (finalizers) are only run when an object is 
collected. No collection, no destructor call.


More information about the Digitalmars-d-learn mailing list