digitalmars.D.learn - Handling referencing class parent instances in a GC friendly way.
- realhet (20/20) Nov 30 2020 Hi,
- FeepingCreature (10/30) Nov 30 2020 The GC will release it anyways. The advantage of a GC is that it
- realhet (5/8) Nov 30 2020 I just forgot 1 of three things, thx for pointing it out.
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!
Nov 30 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.
Nov 30 2020
On Monday, 30 November 2020 at 14:36:08 UTC, FeepingCreature wrote:On Monday, 30 November 2020 at 14:33:22 UTC, realhet wrote: ... Though you may want to do `items = null;` too.I just forgot 1 of three things, thx for pointing it out. And I also forget to notify the parent to remove the reference from its items list.
Nov 30 2020