Destructor called while object is still alive

frame frame86 at live.com
Fri Oct 23 06:15:32 UTC 2020


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?

I expect that either GC will not touch the object or only if no 
reference is on the object anymore.

If the object is used in the loop, this will not happen but the 
GC or compiler should not decide to kill the object if a valid 
pointer is still in current scope? Even this is a "intelligent" 
feature by the compiler for non reachable code like that loop, 
it's still confusing. There are maybe situations while the object 
should stay in background, eg. socket related/event stuff. If 
there is a valid pointer, there is no excuse to reap it.


class Foo {
     ~this() {
         writefln("Warning: destructor called (%s) on %s", 
typeid(this), this.__vptr);
     }
}

class Bar {
     static Foo create() {
         return new Foo();
     }
}

void main() {
     auto foo = Bar.create();
     writefln("address: %s", foo.__vptr);

     while(true) {
         Thread.sleep(1.seconds);
         GC.collect();
     }
}

// DMD32 v2.094.1 -m64 on windows


More information about the Digitalmars-d mailing list