digitalmars.D.learn - Can I call GC.addRoot from constructor and trigger collection with destroy()?
- =?iso-8859-1?Q?Robert_M._M=FCnch?= (11/11) Jul 01 2018 I'm creating a bunch of objects and need to use these object pointers
- Steven Schveighoffer (10/19) Jul 02 2018 If you call destroy, it does nothing for the GC. As long as it's not a
I'm creating a bunch of objects and need to use these object pointers with C code. Hence I need to protect them from being GC with GC.addRoot. Can this call be made out of a constructor? So that I can protect the objects as earyl as possible? Could I then unprotect the memory inside the destructor, which I would call explicitly via destroy(...)? Or would a call to destroy be sufficient to tell the GC, now you can collect the memory? -- Robert M. Münch http://www.saphirion.com smarter | better | faster
Jul 01 2018
On 7/1/18 5:59 PM, Robert M. Münch wrote:I'm creating a bunch of objects and need to use these object pointers with C code. Hence I need to protect them from being GC with GC.addRoot. Can this call be made out of a constructor? So that I can protect the objects as earyl as possible?Yes.Could I then unprotect the memory inside the destructor, which I would call explicitly via destroy(...)? Or would a call to destroy be sufficient to tell the GC, now you can collect the memory?If you call destroy, it does nothing for the GC. As long as it's not a class, the GC will actually re-destruct the item when running a collection. And yes, it is possible to removeRoot inside the dtor. However, I'd caution one thing -- addRoot on an already-existing root does not add it again. So you will cause problems if you make copies of the struct that removes the root. The first destructor will remove the root, and then it's free to be collected. -Steve
Jul 02 2018