How it works...

To better understand how RAII works, we must first examine how a class in C++ works as C++ classes are used to implement RAII. Let's look at a simple example. C++ classes provide support for both constructors and destructors as follows:

#include <iostream>#include <stdexcept>class the_answer{public:    the_answer()    {        std::cout << "The answer is: ";    }    ~the_answer()    {        std::cout << "42\n";    }};int main(void){    the_answer is;    return 0;}

This results in the following when compiled and executed:

In the preceding example, we create a class with both a constructor and a destructor. When we create an instance of the class, the constructor ...

Get Advanced C++ Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.