Destructor/Finalizer Guarantees

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Nov 11 18:38:56 PST 2014


On 11/11/14 5:31 PM, Maxime Chevalier-Boisvert wrote:
> I have a situation where I have a VM (virtual machine) object, and
> several GCRoot (garbage collector root objects). The GCRoots are structs
> and will "register" themselves into a linked list belonging to the VM.
> I've made it so they unregister themselves in their destructor. This
> works perfectly well for GC roots which are on the stack.
>
> However, recently, I ran into a case where I need GCRoots which are not
> on the stack. This is where things broke down. The VM object got
> destroyed before the GCRoots, and when these tried to unregister
> themselves, they accessed memory which had already been reclaimed (the
> dead VM). What I want to know is: what guarantees can I expect from
> destructor behavior?
>
> I was thinking that when the VM gets destroyed, it could unregister all
> of its GCRoots at once. Then, when these are destroyed, they wouldn't
> try to touch the VM object. However, this only works if I can assume
> that the GC will first call the destructor on an object, then free the
> object, that this is done in a predictable order. Am I on the right
> track, or do I need to rethink this?

Short answer, you have no guarantees that references to GC memory still 
point at valid memory.

It is a very sticky problem to deal with. Reference counting and GC 
don't mix well, because the GC cannot guarantee destruction order.

-Steve


More information about the Digitalmars-d-learn mailing list