RAII who?

Daniel Keep daniel.keep.lists at gmail.com
Sat May 19 04:42:49 PDT 2007



Jan Hanselaer wrote:
> Hi
> 
> I'm confused about what's meant with Resource Acquisition Is Initialisation. 
> Can somebody explain this, especially how it is accomplished in D?
> Some questions that  arise in my brain when reading and thinking about it.
> 
> - Giving each variable a default value is this part of RAII? Or has it 
> nothing to do with it?

Nothing to do with it.  Initialisation to a default value is just
something to help catch bugs.  For integer types, this doesn't really do
much, but floating-point, character and reference types, they all get
"invalid" values which make it pretty obvious when you've forgotten to
initialise something.

> - What's the use of the keyword 'auto' in the whole story?

It isn't.  It *used* to be the way to trigger RAII, but not any more.
Now you want the 'scope' keyword.

> - What's the link with garbage collection?

RAII instances of classes do not need to be garbage collected; they are
deterministically destroyed.  See below.

> - If I don't use the keyword auto, memory resources are not automatically 
> freed?

Here's a "normal" class instance declaration:

auto Foo foo = new Foo;

Here, "foo" can either be explicitly destroyed using 'delete', or it
will be garbage collected when nothing refers to it.  On the other hand:

scope Foo foo = new Foo;

What happens here is that "foo" is now scoped.  At the end of the
declaring scope (which could be the function, conditional branch,
current iteration of a loop, etc.), the object will be destroyed and freed.

Please note that, AFAIK, scope doesn't work on any other reference type:
arrays, pointers or associative arrays.

Also note that the above are also equivalent to:

"auto Foo foo = new Foo;"
  == "Foo foo = new Foo;"
  == "auto foo = new Foo;"

"scope Foo foo = new Foo;"
  == "scope foo = new Foo;"

> - ...
> 
> I just don't seem to get te whole picture here. But I suspect it's not that 
> complicated.
> Anyone with a short and clear definition?
> 
> Thanks in advance!
> Jan 

I don't really think of it as "RAII" anymore: I think of it as "scoped
objects" -- objects which live only as long as the current scope.

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/



More information about the Digitalmars-d mailing list