Garbage collector and real resources

Bradley Smith digitalmars-com at baysmith.com
Wed Jan 24 21:51:32 PST 2007


AlexBurton wrote:
> Thanks for your reply Boris
> 
> It appears that I have miscommunicated my problem. I was not intending to say that the scope keyword was not working as documented.
> 
> This line of my original post:
> 
> "The second instance of FileWriter fails because the first is still around even though the scope keyword is used."
> 
> Should have read :
> 
> "The second instance of FileWriter fails because the FileStream that was part of the first has not been destroyed."
> 
> Alex

I got it to work by explicitly deleting the File object in a FileWriter 
destructor. Below is the code. The documentation on destructors 
(http://www.digitalmars.com/d/class.html#destructors) states

"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.

Thanks for the interesting post.
   Bradley


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;
}



More information about the Digitalmars-d mailing list