Closing streams on deletion

Max Samukha samukha at voliacable.com
Fri Jan 26 05:37:53 PST 2007


On Fri, 26 Jan 2007 12:54:30 +0100, Frits van Bommel
<fvbommel at REMwOVExCAPSs.nl> wrote:

>Max Samukha wrote:
>> Are streams supposed to get closed when they are deleted? Currently
>> only file stream seems to work that way (its destructor calls
>> close()).
>> 
>> scope auto file = new File("file.txt");
>> // ok. file is closed at the end of the scope
>> 
>> scope auto file = new EndianStream(new BufferedFile("file.txt"));
>> // I expected the EndianStream's destructor would close the stream and
>> the underlying stream (nestClose is true) but that didn't happen.
>> 
>> It is by design?
>
>It's probably more "by limitation".
>File uses OS handles, so it can close those without any problems. If 
>another Stream needs to be closed though, you can't really do that in 
>the destructor. This is because if the garbage collector is the one 
>calling the destructor, it may have already collected the underlying 
>Stream and calling any methods on it produces Undefined Behavior. Which 
>is a Bad Thing.
>And since there's no way to tell if the object was deleted manually or 
>by the GC, it's best not to touch any other objects in the destructor.

Thanks, Frits. I've overlooked the paragraph in the specs:
"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 are no longer valid."
Shouldn't it be in red bold underlined font? :)


More information about the Digitalmars-d-learn mailing list