GC BUG: Referenced object destroyed before released

Graham St Jack grahams at acres.com.au
Mon Mar 17 21:30:31 PDT 2008


On Mon, 17 Mar 2008 12:34:06 -0400, Steven Schveighoffer wrote:

> "Koroskin Denis" in message
>> On Mon, 17 Mar 2008 01:28:04 +0300, Graham St Jack  wrote:
>>> I agree that this is a problem. Who cares if the two objects in
>>> question aren't referenced and more - their destructors should be
>>> called in the right order if it is possible to do so.
>>
>> Yep.
>>
>>> I guess the work-around (and maybe permanent) is to not reference any
>>> garbage-collected objects in your destructors.
>>>
>>>
>> Nope. This is against RAII pattern.
> 
> The issue is with the usage of the destructor to clean up memory.  Do
> not worry about cleaning up memory in destructors, that is what we have
> the garbage collector for.
> 
> In your example, all the members of Resource are GC allocated and so
> will be cleaned up when Resource is cleaned up.  You shouldn't care what
> the order is.
> 
> If you have an OS resource, such as an open file, that should be cleaned
> up in the destructor of the object which owns the OS handle.  This is
> what destructors are for.
> 
> The only missing piece is if you wanted to have an array of OS
> resources. In order to make sure the elements in this array are cleaned
> up properly, you would need to allocate the array using an alternate
> memory allocator that does not get cleaned up automatically, or else use
> wrapper classes to store the OS resources.  A way to fix this would be
> to always deallocate arrays last in the GC, and allow using the array
> elements (not objects pointed to by those elements) in the destructors.
> 
> -Steve

I get it now. Thanks for the insights. I am too used to manual memory-
management in C++ - using a garbage collector is wonderfully easy by 
comparison, but there are a few tricks to learn even so.



More information about the Digitalmars-d mailing list