Garbage collector collects live objects

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 25 06:51:40 PDT 2015


On 12/09/2014 08:53 AM, Steven Schveighoffer wrote:

 > On 12/9/14 11:17 AM, ketmar via Digitalmars-d-learn wrote:

 >> that file can be already finalized. please remember that `~this()` is
 >> more a finalizer than destructor, and it's called on *dead* object.

Agreed: D has a terminology issue here, what we call a "class 
destructor" is a "class finalizer". I have added D to the Wikipedia article:

   http://en.wikipedia.org/wiki/Finalizer

Now I want to improve some of my chapters.

 >> here this means that any other object in your object (including
 >> structs) can be already finalized at the time GC decides to call your
 >> finalizer.

Although I know the fact above, I think ketmar makes a distinction (that 
is new to me) that a finalizer is a function that does not reference 
class members but a destructor does (or safely can).

 > File is specially designed (although it's not perfect) to be able to
 > close in the GC. Its ref-counted payload is placed on the C heap to
 > allow access during finalization.
 >
 > That being said, you actually don't need to write the above in the class
 > finalizer, _file's destructor will automatically be called.
 >
 >> just avoid "destructors" unless you *really* need that. in your case
 >> simply let GC finalize your File, don't try to help GC. this is not C++
 >> (or any other language without GC) and "destructors" aren't destructing
 >> anything at all. "destructors" must clean up the things that GC cannot
 >> (malloc()'ed memory, for example), and nothing else.
 >>
 >
 > Good advice ;)
 >
 > I would say other than library writers, nobody should ever write a class
 > dtor.
 >
 > -Steve

Can somebody elaborate on that guideline please. Given a case where 
runtime polymorphism is needed, so that we have to use classes, does the 
guideline simply mean that "arrange for manual cleanup" or is there more 
in that guideline? I am confused about the "library writers" part. :)

Thank you,
Ali



More information about the Digitalmars-d-learn mailing list