How to write a proper class destructor?

Jonas Kivi satelliittipupu at yahoo.co.uk
Fri Jan 26 04:13:00 PST 2007


> "Bradley Smith" <digitalmars-com at baysmith.com> wrote in message 

>> How is a class supposed to release something for which it no longer has a 
>> valid reference?

Jarrett Billingsley wrote:
> 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. 
> 
> 

Hmm, I think I've run into this problem just a few days ago, as my own 
(very basic) LinkedList implementation was getting a little bit heavy on 
the GC. So, I thought I might be able to make it a little bit quicker by 
adding a destructor and deleting the Nodes that point to the actual data 
(the Nodes that the LinkedList has created). But suddenly I wasn't able 
to iterate through the Nodes while in the destructor, and so, I wasn't 
able to delete them. I'm not really sure if the GC is causing the one 
second pauses that I get when I'm on a really heavy load doing thousands 
of LinkedLists and releasing them. Maybe I should try using pure D 
dynamic arrays instead of my own container... Or try Tango when it's 
released. Do the dynamic arrays in D, or the Tango containers use GC?

And about the scope keyword on a class member suggestion: What about the 
"auto" keyword. What's the difference between the auto and the scope 
keywords?

class Any
{
	auto SomeOther m_someOther;

	this()
	{
		m_someOther = new SomeOther();
	}

	~this()
	{
		//automatically deletes m_someOther...
	}
}


More information about the Digitalmars-d-learn mailing list