Destructors and Deterministic Memory Management

Georg Wrede georg.wrede at iki.fi
Wed May 6 10:29:50 PDT 2009


Sean Kelly wrote:
> Georg Wrede wrote:
>>
>> Dsimcha wrote "Since the destructor called by the GC can't reference 
>> sub-objects", I got into thinking that we'd then need a myDestructor.
>>
>> But
>>
>>    delete myobject;
>>
>> calls ~this() in myobject, as does the GC, as does program exit.
>>
>> I also tested, and the referenced other objects did get deleted. No 
>> problem. That implies releasing other resources works, by simply 
>> having such release code in ~this() for the object.
>>
>> I found no difference in calling delete or letting the GC do it. So, 
>> originally dsimcha's problem was imagined?
> 
> If an object might possibly be finalized by the GC rather than deleted 
> explicitly then its dtor can't referfence subobjects (because the GC 
> doesn't guarantee any particular finalization order).  These subobjects 
> will be finalized by the GC anyway when it detects that they're no 
> longer referenced, but sometimes it's nice to do something with these 
> objects when you know they're still valid.  My example provided a way 
> for a different routine to be called for deterministic vs. 
> non-deterministic finalization to allow for this.

I've always found that sentence a bit murky in the docs. Thinking more, 
isn't this what happens:

class A {
    A b = new A;
}
void main() { A c = new A;}

When ca gets collected, it is not "guaranteed" that b gets distroyed 
first. Fine. But suppose A has a destructor that says delete b. Wouldn't 
that guarantee that b gets destroyed before c? And if so, shouldn't the 
sentence in the docs be changed somehow so it doesn't send folks on "a 
reverse goose chase, meaning running scrared of the geese".




More information about the Digitalmars-d mailing list