strange work of GC

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 7 16:20:37 PST 2015


On 2/8/2015 4:32 AM, Andrey Derzhavin wrote:
>> Why do you want to use destroy?
> The destroy method always calls a dtor of the objects, where I can
> destroy some
> object's variables in that order that I need, I think. And this is very
> good for me, because I have a full control of the object's destroying
> stage.
> But if I use the GC, I have no garanties that the dtors will be called,
> therefore some of my methods will not be called too. In this case
> it would be better to disable automatically garbage collection in my D
> app, elsewise once app will be failed (manual destroying idiom).
>
> On another hand if I use only GC (automatically destroying idiom), I
> have to disable "destroy" method and all dtors of the objects,
> so that nobody can call "destroy" method. Otherwise app will be failed
> once again.
>
> Two idioms are existing in one app at the same time have more
> possiblities for D programmers to make hard errors in their code,
> and it is confusing me sometimes.
>
> For example, .Net (C#) have no dtors and "destroy" methods. It is a very
> good idiom, because no confusions occur.

You shouldn't think of destructors as they are in C++. They're more akin 
to finalizers in Java and C#. You should never use them to clean up any 
GC memory or implement any operations which touch GC memory.

In your case, forget destructors and the destroy method. Just implement 
a common method on all of your objects that need cleanup (perhaps name 
it 'terminate') and call that. This gives you the deterministic 
destruction that you want (the same as calling destroy on each object) 
while avoiding the possibility that the GC can call your cleanup method.


More information about the Digitalmars-d-learn mailing list