What is legal in a destructor?

Jarrett Billingsley kb3ctd2 at yahoo.com
Sun Aug 27 10:02:54 PDT 2006


"Lutger" <lutger.blijdestijn at gmail.com> wrote in message 
news:ecruhp$2hug$1 at digitaldaemon.com...
> I'm having some trouble understanding exactly what is and what isn't legal 
> to do in a (non-auto) destructor. I'm thinking about these specifically:
>
> - using the 'this' pointer as a parameter to make calls to another (from 
> another class or free) function.
> - calling member functions.
> - referencing delegates to member functions.
> - referencing data fields with types like int.

As a general rule, you shouldn't try to access any GC'ed memory within a 
destructor.  This means most things allocated by your program, such as 
references to other class instances, arrays, and blocks of memory allocated 
by 'new'.  When the destructor is run, the 'this' pointer is still valid, so 
you can call other member functions and use it as a parameter, but again, 
those functions shouldn't access GC'ed memory.

I mostly use destructors to clean up non-GC'ed resources, such as system 
resources (file handles, COM interfaces etc.).  I also set references to 
GC'ed memory to null, which isn't really required, but it might make the 
GC's job a little easier. 





More information about the Digitalmars-d-learn mailing list