Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the compiler decide the noexcept'ness of a function?

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?

like image 225
Mattia F. Avatar asked Aug 02 '16 09:08

Mattia F.


People also ask

What is a noexcept function in C++?

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

How do you mark a function as noexcept?

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.

What is the use of noexcept keyword in JavaScript?

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.

Can a template function that copies its argument be declared noexcept?

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:


1 Answers

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.

like image 191
alain Avatar answered Sep 28 '22 14:09

alain