How to write a proper class destructor?

Jarrett Billingsley kb3ctd2 at yahoo.com
Thu Jan 25 06:43:24 PST 2007


"Bradley Smith" <digitalmars-com at baysmith.com> wrote in message 
news:ep9joi$1mr2$1 at digitaldaemon.com...
> According to the documentation, a class destructor is "expected to release 
> any resources held by the object."[1] However, if resources to be released 
> are in objects to be garbage collected, "those references are no longer 
> valid."[1]
>
> How is a class supposed to release something for which it no longer has a 
> valid reference?

Huuaaaahhh!

I remember someone suggesting that 'scope' be a valid modifier for class 
instance variables, and it'd basically mean "when this class gets destroyed, 
destroy this other instance as well."  Like auto-deletion when you use a 
scope reference in a function:

class ResourceHolder
{
    scope SomeResource mRsrc;

    this(char[] name)
    {
        mRsrc = new SomeResource(name);
    }
}

..

{
    scope holder = new ResourceHolder("a.file");
    ...
} // holder is destroyed here, and so is its mRsrc member.

Another solution would be to change the behavior of the GC so that deletion 
on program end _is_ deterministic.  That is, it'd basically run a collection 
sweep, call finalizers on objects which don't have references to them, and 
keep doing that until nothing is left.  That way, references to other 
classes would always be valid in destructors, since the GC wouldn't collect 
those references until everything that points to them is destroyed. 




More information about the Digitalmars-d-learn mailing list