Handling referencing class parent instances in a GC friendly way.

FeepingCreature feepingcreature at gmail.com
Mon Nov 30 14:36:08 UTC 2020


On Monday, 30 November 2020 at 14:33:22 UTC, realhet wrote:
> Hi,
>
> class A{
>   A parent;
>   A[] items;
>
>   void myDestroy(){
>     items.each!(i => i.myDestroy);
>     parent = null;
>     // after this point I think the GC will release it 
> automatically, and it will call ~this() too. Am I right?
>   }
> }
>
> I have a hierarchy of class instances forward and backward 
> linked to its items ant its parent.
>
> What is a proper way to destroy an instance of class A? Is 
> calling instance.myDestroy sufficient?
>
> Am I right that this kind of uninitialization MUST not go into 
> the ~this() destructor, because of the references the instance 
> is holding, the system will never call the ~this()?
>
> Or is there a better way for this type of thing in Dlang?
>
>
> Thanks in advance!

The GC will release it anyways. The advantage of a GC is that it 
is not deterred by cyclic references, so as soon as no more 
references into A exist, it will disappear, no matter the parent 
pointer.

At least, that's the theory - in practice, since we don't have 
precise stack GC, any spurious or leftover pointer to an A can 
keep the whole tree alive, so the myDestroy cleanup method is 
still valid and recommended. Though you may want to do `items = 
null;` too.


More information about the Digitalmars-d-learn mailing list