Segmentation fault on closing file in destructor

"Jérôme M. Berger" jeberger at free.fr
Sun Sep 26 13:59:22 PDT 2010


Tom Kazimiers 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? 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?
> 
	The way I see it, there are two possible situations:

1. You really need precise control as to when the file is closed. In
that case, your class contains an explicit cleanup function that you
call before dropping the last reference and you can close the file
at that time;

2. You only need to be sure that the file gets closed at some point
but it doesn't really signify when. In that case, you let the GC
collect your class and you don't close the file. Eventually the GC
will collect the std.stream.File instance which will result in
calling its destructor which will close the file without your
needing to do anything about it.

		Jerome
-- 
mailto:jeberger at free.fr
http://jeberger.free.fr
Jabber: jeberger at jabber.fr


More information about the Digitalmars-d-learn mailing list