Resource Acquisition Is Initialization (RAII) is a programming idiom that attempts to prevent the risk of leaking memory and other resources. It is only applicable to languages that have predictable object destroyment, and among these is C++ (an object's destroyer method is always called when it goes out of scope).

The basic idea behind RAII is to wrap any resource subject to be leaked in a thin class. This class acquires the resource during its construction and releases it upon destroyment, thus hiding all the internal details from the user. This way, these resources are always released, no matter if the function has multiple exit points or throws an exception, because the destroyer will be automatically called for existing objects.

If you have ever written C++ code, you have probably already used RAII without knowing it. In fact, I just learned today that this technique has a name, while I've been using it for a long time :-)

I suggest you to read this article from Jon Hanna; it discusses this topic in great detail.

Subscribe via RSS · Go to posts index

   Delivered by FeedBurner

Comments from the original Blogger-hosted post: