destructors and GC again

Lutger lutger.blijdestijn at gmail.com
Mon Oct 16 08:42:35 PDT 2006


Derek Parnell wrote:
> On Mon, 16 Oct 2006 16:36:52 +0200, Lutger wrote:
> 
>> Sorry for this topic again, I'm still not exactly sure: when an 
>> unreferenced object is collected during the lifetime of your program 
>> (before main exits), is the destructor of this object guaranteed to be 
>> called? I expect it to be so, as otherwise destructors seem pretty 
>> useless (and dangerous), but cannot infer this from the spec.
>>
>> The spec says: "The garbage collector is not guaranteed to run the 
>> destructor for all unreferenced objects ... The garbage collector calls 
>> the destructor function when the object is deleted."
>>
>> It's not clear from this to me that IF an object is collected (of which 
>> you cannot be sure, ok), what is guaranteed about the destructor. I 
>> assume 'deleted' in the spec means that delete is explicitly called, not 
>> 'collected by the GC'.
> 
> I don't think that it is guaranteed. You need to either explicitly delete
> it or use 'auto' (meaning RAII this time).
> 
> e.g.
> 
>   void somefunc()
>   {
>     auto MyClass X = new MyClass();
>   }
> 
> or
> 
>   void somefunc()
>   {
>     MyClass X = new MyClass();
>     scope(exit) { delete X; }
>   }
>     
> 

Really? That would be so foobar. I'm trying to rewrite my half-broken 
signal-slots lib, the C-heap hack I have figured out. (Cannot use auto 
for this). But I think I need such a guarantee for destructors.

This is sort of what I want to achieve:

1. Store a delegate from a member function in C-heap to be used as a 
callback, so this callback won't prevent GC from collecting the object 
the callback is taken from.
2. At some point this object is collected by GC.
3. Now the stored callback should be removed, otherwise invoking the 
callback later in time is a no-no of course. This is done from the 
destructor of the collected object.

If 3) is not guaranteed to occur (before main exits, after that it 
doesn't matter), then I don't see a way to garbage collect these 
callbacks, which leaves me with the following options:
a) don't use the C-heap and just leak memory which the user must 
manually clean up.
b) rely on the user to call delete, avoiding GC altogether. (not a good 
idea)

Both options are not very satisfying, and perhaps even defy the point of 
such a library. Maybe I'm missing something here?



More information about the Digitalmars-d-learn mailing list