Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Part One.  Fundamentals


Chapter 6. Scoping Classes

In section 3.5 we looked at the definition of Resource Acquisition Is Initialization (RAII), and in this chapter we're going to demonstrate some of the different ways in which it can be applied.

RAII is singularly potent when it comes to resource management. We expect that when a vector<string> goes out of scope, its destructor is called and it releases its contents. As part of this process, all the contained string instances are also destroyed and release their resources, after which the memory block that the vector used to store the string instances is released back to the free store. You get all that functionality just by typing a }.

The treatment here is pure RAII: a scoping instance acquires a resource in its constructor and faithfully releases it in its destructor. Nevertheless, what is perhaps not widely considered is that the mechanism can support a very wide definition of "resource." In this chapter I hope to demonstrate that RAII is suitable, indeed desirable, to be applied to things other than memory blocks and file-handles. We will see how such resources can include values, states, APIs, and even language features.


      Previous section   Next section