Closing streams on deletion

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Fri Jan 26 03:54:30 PST 2007


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.


More information about the Digitalmars-d-learn mailing list