Let's do an example
class X
{
int value;
public:
X (int def = 0) : value (def) {}
void add (int i)
{
value += i;
}
};
Clearly, the function void X::add (int)
will never throw any exception.
My question is, can the compiler analyze the code and decide not to generate machine code to handle exceptions, even if the function is not marked as noexcept
?
The noexcept-specification is a part of the function type and may appear as part of any function declarator . Every function in C++ is either non-throwing or potentially throwing : functions declared with a non-empty dynamic exception specification functions declared with noexcept specifier whose expression evaluates to false
Mark a function as noexcept only if all the functions that it calls, either directly or indirectly, are also noexcept or const. The compiler doesn't necessarily check every code path for exceptions that might bubble up to a noexcept function.
In short, we use noexcept keyword with those lines of code that does not cause an exception, and if they cause we can ignore it. This noexcept takes a boolean value as true or false in order to specify whether the function is supposed to throw an exception or not.
A template function that copies its argument might be declared noexcept on the condition that the object being copied is a plain old data type (POD). Such a function could be declared like this:
If the compiler can prove that a function will never throw, it is allowed by the "As-If" rule (§1.9, "Program execution" of the C++ standard) to remove the code to handle exceptions.
However it is not possible to decide if a function will never throw in general, as it amounts to solving the Halting Problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With