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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.