Recommended way to do RAII cleanly

Jonathan M Davis jmdavisprog at gmail.com
Mon Jul 12 15:08:59 PDT 2010


On Monday, July 12, 2010 13:17:04 torhu wrote:
> For you hourglass example, wouldn't you need to call two methods anyway?
> I googled for "MFC hourglass". Then it'd look like this:
> 
> BeginWaitCursor();
> scope (exit) EndWaitCursor();

I haven't used MFC recently, I'm 99% certain that there's a class in MFC that 
wraps this for you so that all you have to do is declare a local variable of 
that type, and the hourglass is visible until that variable leaves scope and is 
destroyed. If it's not MFC, then the shop that I was working at had their own 
class that did that.

> 
> The Mutex in Phobos is a class, so you'd have to do basically the same
> thing. But if you only need a local mutex, you'd probably use a
> synchronized statement instead.

It's not the mutex but an autolock for a mutex which would use RAII. It would 
lock the mutex when it was declared and unlock when it left scope and was 
destroyed. However, since you'd have to give it the mutex as a parameter (as 
opposed to using a default constructor), the lack of default constructor 
wouldn't be an issue. For the most part synchronized deals with the issue 
though. My one concern with synchronized is how you'd unsynchronize in the 
middle of the synchronized block if you had to (but that's a separate issue and 
a likely cause for having to use mutexes instead of synchronized).

> 
> I think the conclusion is that RAII is less important in D than in C++.
>   In D you use scope (exit), or even finally, like in Java or Python.
> The other use of scope, as a storage class, is supposed to go away, and
> I suspect I'm not the only one who's going to miss it.

There are lots of cases where using scope(exit) makes sense, and it's a great 
construct. But there are also plenty of cases where using plain old RAII with a 
single declaration is better. It works fine in D as long as the struct in 
question doesn't need a default constructor. But if it does, then it becomes a 
problem.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list