The RAII idiom
We have seen in the previous section how ad hoc attempts to manage resources become unreliable, then error-prone, and eventually fail. What we need is to make sure that resource acquisition is always paired up with resource release, and that these two actions happen before and after the section of code that uses the resource respectively. In C++, this kind of bracketing of a code sequence by a pair of actions is known as the Execute Around design pattern.
Tip
For more information, see the article C++ Patterns – Executing Around Sequences by Kevlin Henney, available at http://www.two-sdg.demon.co.uk/curbralan/papers/europlop/ExecutingAroundSequences.pdf.
When specifically applied to resource management, this pattern is much more widely known as Resource Acquisition is Initialization (RAII).
RAII in a nutshell
The basic idea behind RAII is very simple—there is one kind of function in C++ that is guaranteed to be called automatically, and that...