Garbage collector and real resources

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Thu Jan 25 01:36:55 PST 2007


Bradley Smith wrote:
[snip]
> "The garbage collector is not guaranteed to run the destructor for all 
> unreferenced objects. Furthermore, the order in which the garbage 
> collector calls destructors for unreference objects is not specified."
> 
> This makes me wonder how to reasonably release resources held by an 
> object. I'll be asking this question on digitalmars.D.learn.

> import std.stream;
> 
> class FileWriter
> {
>   std.stream.File f;
>   this()
>   {
>     f = new std.stream.File("data.txt",FileMode.Out);
>     f.write(23);
>   }
>   ~this()
>   {
>     delete f;
>   }
> }
> 
> int main()
> {
>   {
>     scope auto f = new FileWriter();
>   }
>   {
>     scope auto f = new FileWriter();
>   }
> 
>   return 0;
> }

Note that code may have undefined behavior if FileWriter is ever deleted 
by the GC. In that case, the std.stream.File may have been collected 
before the FileWriter (that's what the unspecified order of destructors 
means), and you're performing a double deletion.
So if you delete f in the destructor, it may be best to make FileWriter 
a scope class (add 'scope' before 'class') so that it's always 
explicitly deleted.



More information about the Digitalmars-d mailing list