Book Image

Advanced C++ Programming Cookbook

By : Dr. Rian Quinn
Book Image

Advanced C++ Programming Cookbook

By: Dr. Rian Quinn

Overview of this book

If you think you've mastered C++ and know everything it takes to write robust applications, you'll be in for a surprise. With this book, you'll gain comprehensive insights into C++, covering exclusive tips and interesting techniques to enhance your app development process. You'll kick off with the basic principles of library design and development, which will help you understand how to write reusable and maintainable code. You'll then discover the importance of exception safety, and how you can avoid unexpected errors or bugs in your code. The book will take you through the modern elements of C++, such as move semantics, type deductions, and coroutines. As you advance, you'll delve into template programming - the standard tool for most library developers looking to achieve high code reusability. You'll explore the STL and learn how to avoid common pitfalls while implementing templates. Later, you'll learn about the problems of multithreaded programming such as data races, deadlocks, and thread starvation. You'll also learn high-performance programming by using benchmarking tools and libraries. Finally, you'll discover advanced techniques for debugging and testing to ensure code reliability. By the end of this book, you'll have become an expert at C++ programming and will have gained the skills to solve complex development problems with ease.
Table of Contents (15 chapters)

Learning why to never throw exceptions in destructors

In this recipe, we will discuss the issues with C++ exceptions, specifically in regard to throwing exceptions within a class destructor, something that should be avoided at all costs. The lessons learned in this recipe are important because, unlike other functions, a C++ class destructor is marked as noexcept by default, which means that if you accidentally throw an exception inside a class destructor, your program will call std::terminate(), even though the destructor my not be overtly labeled noexcept.

Getting ready

Before beginning, please ensure that all of the technical requirements are met, including installing Ubuntu 18.04 or higher, and run the following in a Terminal window:

> sudo apt-get install build-essential git cmake

This will ensure your operating system has the proper tools to compile and execute the examples in this recipe. Once this is complete, open a new Terminal. We will use this Terminal to download, compile, and run our examples.

How to do it...

Perform the following steps to try the recipe:

  1. From a new Terminal, run the following to download the source code:
> cd ~/
> git clone https://github.com/PacktPublishing/Advanced-CPP-CookBook.git
> cd Advanced-CPP-CookBook/chapter02
  1. To compile the source code, run the following:
> mkdir build && cd build
> cmake ..
> make recipe04_examples
  1. Once the source code is compiled, you can execute each example in this recipe by running the following commands:
> ./recipe04_example01
terminate called after throwing an instance of 'std::runtime_error'
what(): 42
Aborted

> ./recipe04_example02
The answer is: 42

> ./recipe04_example03
terminate called after throwing an instance of 'std::runtime_error'
what(): 42
Aborted

> ./recipe04_example04
# exceptions: 2
The answer is: 42
The answer is: always 42

In the next section, we will step through each of these examples and explain what each example program does and how it relates to the lessons being taught in this recipe.

How it works...

In this recipe, we will learn why throwing exceptions in a destructor is a bad idea, and why class destructors are labeled as noexcept by default. To start, let's look at a simple example:

#include <iostream>
#include <stdexcept>

class the_answer
{
public:
~the_answer()
{
throw std::runtime_error("42");
}
};

int main(void)
{
try {
the_answer is;
}
catch (const std::exception &e) {
std::cout << "The answer is: " << e.what() << '\n';
}
}

When we execute this, we get the following:

In this example, we can see that if we throw an exception from a class destructor, std::terminate() is called. This is because, by default, a class destructor is marked as noexcept.

We can change this by explicitly allowing a class destructor to throw by marking the class's destructor as noexcept(false), as shown in the next example:

#include <iostream>
#include <stdexcept>

class the_answer
{
public:
~the_answer() noexcept(false)
{
throw std::runtime_error("42");
}
};

int main(void)
{
try {
the_answer is;
}
catch (const std::exception &e) {
std::cout << "The answer is: " << e.what() << '\n';
}
}

As shown in the preceding example, when the class is destroyed, an exception is thrown and properly handled. Even though this was successfully handled, we have to ask ourselves, what is the state of the program after we catch this exception? The destructor didn't successfully complete. If this class was more complex and had state/resources that it was managing, can we conclude that the state/resources that we care about were properly handled/released? The short answer is no. This is the same as destroying a hard drive with a hammer. If you slam a hard drive with a hammer to destroy it, did you actually destroy the data on the hard drive? There is no way to know because, when you hit the hard drive with the hammer, you broke the electronics that would have been used to answer that very question. When you attempt to destroy a hard drive, you need a reliable process that ensures that, under no circumstance could the process of destroying the drive leave data in a recoverable state. Otherwise, you have no way of knowing what state you are in, with no way of going back.

The same applies to C++ classes. Destroying a C++ class needs to be an operation that must provide basic exception safety (that is, the state of the program is deterministic with some possible side effects). Otherwise, the only other logical course of action is to call std::terminate() since you cannot be sure what will happen if the program continues to execute.

Besides putting the program in an undefined state, the other issue with throwing an exception from a destructor is, what happens if an exception has already been thrown? What does the try/catch block catch? Let's look at an example of this type of issue:

#include <iostream>
#include <stdexcept>

class the_answer
{
public:
~the_answer() noexcept(false)
{
throw std::runtime_error("42");
}
};

int main(void)
{
try {
the_answer is;
throw std::runtime_error("first exception");
}
catch (const std::exception &e) {
std::cout << "The answer is: " << e.what() << '\n';
}
}

In the preceding example, we mark the destructor as noexcept(false) just like we did in the previous example, but we throw before the destructor is called, which means that, when the destructor is called, there is already an exception being processed. Now, when we attempt to throw, std::terminate() is called even though the destructor was marked as noexcept(false):

The reason for this is the C++ library has no way of handling this situation because the try/catch block cannot handle more than one exception. It is possible, however, to have more than one pending exception; we simply need a try/catch block to handle each exception. This situation occurs when we have nested exceptions, as in this example:

#include <iostream>
#include <stdexcept>

class nested
{
public:
~nested()
{
std::cout << "# exceptions: " << std::uncaught_exceptions() << '\n';
}
};

class the_answer
{
public:
~the_answer()
{
try {
nested n;
throw std::runtime_error("42");
}
catch (const std::exception &e) {
std::cout << "The answer is: " << e.what() << '\n';
}
}
};

In this example, we will start by creating a class that outputs the results of calling std::uncaught_exceptions(), which returns the total number of exceptions currently being processed. We will then create a second class that creates the first class and then throws from its destructor, with the important note that all of the code in the destructor is wrapped in a try/catch block:

int main(void)
{
try {
the_answer is;
throw std::runtime_error("always 42");
}
catch (const std::exception &e) {
std::cout << "The answer is: " << e.what() << '\n';
}
}

When this example is executed, we get the following:

Finally, we will create this second class and throw again with another try/catch block. Unlike the previous example, all of the exceptions are being properly handled, and, in fact, noexcept(false) is not needed to ensure that this code executes properly as, for each exception that is thrown, we have a try/catch block. Even though an exception was thrown inside a destructor, it was properly handled, which means that the destructor executes safely and remains noexcept-compliant, even though the second class is executing in the presence of the two exceptions being processed.