Can I call GC.addRoot from constructor and trigger collection with destroy()?
Steven Schveighoffer
schveiguy at yahoo.com
Mon Jul 2 17:31:01 UTC 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
More information about the Digitalmars-d-learn
mailing list