destructors and GC again

Derek Parnell derek at psyc.ward
Mon Oct 16 07:56:45 PDT 2006

On Mon, 16 Oct 2006 16:36:52 +0200, Lutger wrote:

> Sorry for this topic again, I'm still not exactly sure: when an 
> unreferenced object is collected during the lifetime of your program 
> (before main exits), is the destructor of this object guaranteed to be 
> called? I expect it to be so, as otherwise destructors seem pretty 
> useless (and dangerous), but cannot infer this from the spec.
> The spec says: "The garbage collector is not guaranteed to run the 
> destructor for all unreferenced objects ... The garbage collector calls 
> the destructor function when the object is deleted."
> It's not clear from this to me that IF an object is collected (of which 
> you cannot be sure, ok), what is guaranteed about the destructor. I 
> assume 'deleted' in the spec means that delete is explicitly called, not 
> 'collected by the GC'.

I don't think that it is guaranteed. You need to either explicitly delete
it or use 'auto' (meaning RAII this time).


  void somefunc()
    auto MyClass X = new MyClass();


  void somefunc()
    MyClass X = new MyClass();
    scope(exit) { delete X; }

Derek Parnell
Melbourne, Australia
"Down with mediocrity!"

More information about the Digitalmars-d-learn mailing list