Shouldn’t RAII should be RDID???

I will openly plead ignorance for design patterns. I know this is really not the way to be and Design Patterns and Code Complete are on my “to read” list. It’s only that I trawl through StackOverflow a bit lately that I get to hear a lot of buzz about patterns and idioms. Some people get really obsessive about identifying the patterns and making sure they use the right one. But that’s not really the point of this post.

Most of the time I realize that a lot of those pattens is osmething that I have been doing for years without thinking. In fact this inspires me to go through “the list” of all the patterns and do a series of blog posts – “Design Patterns – What you have coded for years is actually an idiom – [insert design pattern here]“.

So, I only just recently found out that the practice of using smart pointers is officially called RAII – Resource Allocation Is Initialization. The Wikipedia article bangs on about ojects being allocated on the stack and exception safety, but in my opinion those considerations are not as significant as the magic of destruction.

The only way this works in C++ is due to deterministic destructors. The magic happens upon destruction, not upon initialization. Any garbage collected language can have Allocation on Initialization, but they can’t guarantee implicit destruction when going out of scope like C++ does.

I also think that that object scope (the fact that it should be on the stack) is somewhat peripheral again. The destructor will get called whenever you explicitly delete the object as well. Whilst this is not strictly automagic destruction, it can be – for example when using collections that are aware of element removal semantics. For example a collection might either call a Release method on a ref counted object or call operator delete on plain old pointer.

So this brings me back to the title of hte post – shouldn’t Resource Allocation Is Initialization be Resource Deallocation Is Destruction? That’s where the magic happens, right?

/***********************
******* Comments *******
***********************/

  1. rmn

    I couldn’t agree more about what you said on design patterns :) I think that the fact that the design patterns only give a name to something most of us have been doing anyway, is just great – it makes it easier to discuss such practices and formalize the design decisions we make. It basically provides us with a proper terminology.

    Regarding RAII.. Well, perhaps you are right :) The most important aspect of it is indeed the fact that the destructor is guaranteed to work, no matter what happens – be it a rogue exception, regular termination of the code block, anything.

    Thanks for the read.

Leave a Reply