Segmentation fault on closing file in destructor

Steven Schveighoffer schveiguy at yahoo.com
Mon Sep 27 05:15:29 PDT 2010


On Sun, 26 Sep 2010 11:17:07 -0400, Tom Kazimiers <2voodoo at gmx.de> wrote:

> Hi Simen,
>
> On 09/26/2010 04:06 PM, Simen kjaeraas wrote:
>> Likely, it is this[1]:
>>
>> "[T]he order in which the garbage collector calls destructors for
>> unreference objects is not specified. This means that when the garbage
>> collector calls a destructor for an object of a class that has members
>> that are references to garbage collected objects, those references may
>> no longer be valid. This means that destructors cannot reference sub
>> objects."
>>
>> [1]: http://digitalmars.com/d/2.0/class.html#destructors
>
> thanks for your reply. I did not know that the garbage collector works
> that way. Is the reason for that flexibility for the GC? What if I want
> to handle some destruction parts to sub-objects or if I want conditions
> while destruction, based on sub-objects?

Then do not use a destructor.  There is no way currently for the  
destructor to know whether it's being called from the GC or not, so it is  
only safe to destroy resources *not* allocated by the GC.  In fact, the  
only reason destructors are supported in classes is to destroy non-GC  
resources.

> Or maybe I should generally
> avoid situations like that. Do you have any suggestion how I should make
> sure that the file gets closed on destruction?

You don't have to worry about it -- let the GC do its job.  If you think  
about it, your class instance may have the only reference to the File  
object.  Since your class is being destroyed by the GC, it makes sense  
that the File object has no references to it, so it too is being destroyed  
by the GC.  If you want sooner destruction, you should manually close it  
earlier via another function call (like close() or detach()).

However, I will mention something that others missed, unlike in C++, the  
default protection in a class is public, so your public: attribute doesn't  
do much, and your file member is publicly accessible.

-Steve


More information about the Digitalmars-d-learn mailing list