How it works...

In this recipe, we will learn why it is so important to mark a function as noexcept if it shouldn't throw an exception. This is because it removes the added overhead to the application for exception support, which can improve execution time, application size, and even load time (this depends on the compiler, which Standard Library you are using, and so on). To show this, let's create a simple example:

class myclass
{
int answer;

public:
~myclass()
{
answer = 42;
}
};

The first thing we need to do is create a class that sets a private member variable when it is destructed, as follows:

void foo()
{
throw 42;
}

int main(void)
{
myclass c;

try {
foo();
}
catch (...) {
}
}

Now, we can create two functions. The first function throws an exception, while the second function is our main function. This function creates an instance of our class and calls the foo() function inside a try/catch block. In other words, at no time will the main() function throw an exception. If we look at the assembly for the main function, we'll see the following:

As we can see, our main function makes a call to _Unwind_Resume, which is used by the exception unwinder. This extra logic is due to the fact that C++ has to add additional exception logic to the end of the function. To remove this extra logic, tell the compiler that the main() function isn't thrown:

int main(void) noexcept
{
myclass c;

try {
foo();
}
catch (...) {
}
}

Adding noexcept tells the compiler that an exception cannot be thrown. As a result, the function no longer contains the extra logic for handling an exception, as follows:

As we can see, the unwind function is no longer present. It should be noted that there are calls to catch functions, which are due to the try/catch block and not the overhead of an exception.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset