RAII who?

Lutger lutger.blijdestijn at gmail.com
Sat May 19 05:47:30 PDT 2007


Jan Hanselaer wrote:
> Thanks for the explanation Daniel en Lutger.
> 
> Some new qestions come to my mind. Since now there is the 'scope' attribute, 
> the auto attribute only exists for type inference?
> 
> I have a background in Java and consequently not used to work with 
> destructors. But in D apparently it is used although there is a garbage 
> collector.
> Are there any (style) rules that say when the scope attribute (and a 
> destructor) is needed?
> I would expect the garbage collector cleaning up all the resources when an 
> object gets out of scope ... So till now I never used a destructor and/or 
> the scope attribute.
> 
> Jan
> 

I think the main issue is lifetime. A garbage collector can decide to 
not collect your unreferenced objects because there is no need for it. 
Furthermore, the collector will only run on calls to new (or if you poke 
it), so objects will usually persist beyond their scope. Thus your 
expectation that the garbage collector cleans all resources when objects 
go out of scope does not always hold, it cleans them up...eventually 
(which can be program exit)

The main rule I follow is to ask myself if it's better to tie some 
resource to a scope. Think about file handles. You want to open the 
file, read it, and then unlock the handle ASAP. This fits very nicely 
into a scope, either with a scope class FileHandle or scope(exit) 
closeFile().

I think the need for RAII objects in D (and destructors in this context) 
is not so pervasive as in C++, simply because the most prevalent 
resource - memory - is usually handled by the garbage collector. Then 
there is scope(exit/succes/failure) which is very useful too and can do 
what scope classes are sometimes used for more directly.



More information about the Digitalmars-d mailing list