Monday 4 July 2011

[YAGE] Memory Management - RAII

Back to YAGE and memory management methods and this time it'll be a short introduction to RAII.

So what's RAII?
RAII[1][2] which stands for Resource Acquisition Is Initialization is a widely used C++ idiom[3]. The weird name may not tell much. But, if used under some strict conditions, this idiom grants the absolute respect of the resources ownership -pointers included- which spares the developer all the headache of monitoring dynamic memory use.

To assure a 100% efficiency of our RAII approach, at least these conditions must be met:
  • Resources allocation MUST be wrapped only in RAII classes in order to keep the control of ownership inside the RAII clan.
  • RAII classes MUST overload the copy constructor AND the assignment operator even when there's no need for them, otherwise RAII would become troublesome and there'd be no need to use it at all.
  • RAII classes destructors MUST NOT throw exceptions. No class destructor should anyway[4] If, by any misfortune, an exception is thrown in the destructor call, some of the resources may leak and the flood will ravage everything in its way.
and to make this approach more rigorous:
  • RAII classes constructors MUST handle any exception involved in the process of the object construction using the appropriate try-catch block[5]. The exception will be re-thrown to let the developer of the client code know of the problem and the destructor won't be called.

A basic example of an RAII class would be like this:


If the first constructor is called with no arguments, a personal computer will unlikely be able to afford that huge amount of memory and new will throw bad_alloc exception.
Note that I used the C-style array just for illustration, it'd be more convenient and less error-prone to use the STL vector instead. Explaining the why goes beyond the scope of this article so if you can't tell the difference between a regular array and a vector I suggest that you read about STL[6].

---
External links:

[1] http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
[2] http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Resource_Acquisition_Is_Initialization
[3] http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms
[4] http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.9
[5] http://www.cs.technion.ac.il/~imaman/programs/throwingctor.html
[6] http://www.cplusplus.com/reference/stl

No comments:

Post a Comment