Error handling and resource acquisition is initialization
We begin by reviewing the concepts of error handling, and, in particular, writing exception-safe code in C++. The Resource Acquisition Is Initialization (RAII) idiom is one of the primary methods of error handling in C++. We have already dedicated an entire chapter to it, and you will need it here to make sense of what we are about to do. Let’s first recognize the problem we are facing.
Error safety and exception safety
For the rest of this chapter, we will consider the following problem—suppose we are implementing a database of records. The records are stored on disk, but there is also an in-memory index for fast access to the records. The database API offers a method to insert records into the database:
class Record { ... }; class Database { public: void insert(const Record& r); ... };
If the insertion succeeds, both the index and the disk storage are updated...