auto classes and finalizers
kris
foo at bar.com
Mon Apr 10 10:56:53 PDT 2006
Sean Kelly wrote:
> kris wrote:
>
>>
>> On the other hand, all these concerns would melt away if the GC were
>> changed to not invoke the dtor (see related post). The beauty of that
>> approach is that there's no additional keywords or compiler behaviour;
>> only the GC is modified to remove the dtor call during a normal
>> collection cycle. Invoking delete or raii just works as always, yet
>> the invalid dtor state is eliminated. It also eliminates the need for
>> a dispose() pattern, which would be nice ;-)
>
>
> For what it's worth, I think this could be accomplished now (thogh I've
> not tried it) as follows:
>
> Object o = new MyObject;
> gc_setFinalizer( o, null );
Nearly, but not quite the same. This certainly disables the dtor for the
given class, but if you forget to do it, your dtor will called with an
'unspecified' (what Don called non-deterministic) state. Plus, there's
no option for capturing leaks.
I believe it's far better to stop the GC from invoking the dtor in those
cases where the state is unspecified: the system would become fully
deterministic, the need for a dispose() pattern goes away ('delete'/raii
takes over), expensive resources that should be released quickly are
always treated in that manner (consistently) or treated as leaks
otherwise, and the GC runs a little faster.
There's the edge-case whereby someone wants a dtor to be invoked lazily
by the collector, at some point in the future. That puts us back into
the non-deterministic dtor state, and is a model that Mike was
suggesting should be removed anyway (because classes that need to
release something should do so as quickly as possible). I fully agree
with Mike on this aspect, but wonder whether a simple implementation
might suffice instead (GC change only)?
Essentially what I'm suggesting is adding this to the documentation:
"a class dtor is invoked via the use of 'delete' or raii only. This
guarantees that (a) classes holding external or otherwise "expensive"
resources will release them in a timely manner, that (b) that the dtor
will be invoked with a fully deterministic state ~ all memory references
held by a class instance will be valid when the dtor is invoked, and
(c) there's no need for redundant cleanup-patterns such as dispose()"
- Kris
More information about the Digitalmars-d
mailing list