Are all functions "noexcept" if exceptions are disabled?

c++, c++11, gcc, language-lawyer

Solution

The `-fno-exceptions` will prevent you from throwing exceptions, but it can not prevent exceptions being thrown from libraries.

For example, next example will terminate because of not caught exception :

#include <vector>

int main()
{
    std::vector<int> v{1,2,3,4,5,6};

    return v.at(55);
}

But next example will not compile, because of `-fno-exceptions` option :

int main()
{
    throw 22;
}

It fails with :

g++   -std=c++11 -g  -Wall -Wextra -fno-exceptions ./garbage.cpp 
./garbage.cpp: In function ‘int main()’:
./garbage.cpp:4:8: error: exception handling disabled, use -fexceptions to enable
  throw 22;

From this article, Doing without chapter :

User code that uses C++ keywords like throw, try, and catch will produce errors even if the user code has included libstdc++ headers and is using constructs like basic_iostream.

On the other hand, `noexcept` marks the method as a method that doesn't throw exceptions. Any thrown exception will call `std::terminate` (see [except.terminate]/2 in c++ standard).

Next example :

struct A
{
    void foo() noexcept
    {
        throw 33;
    }
};

int main()
{
    A a;
    try
    {
        a.foo();
    }
    catch(...)
    {
    }
}

terminates with :

terminate called after throwing an instance of 'int'
Aborted (core dumped)

To conclude : the behavior is quite different when you use `-fno-exceptions` and when you mark the function as `noexcept`.

Although I compile my whole project with -fno-exceptions(for other reasons) I still have to declare move constructors an move assigment operators noexcept to enable move semantic for std::move_if_noexcept?

When you use that option, the functions are not automatically marked as noexcept. You have to do it manually. The compiler is not allowed to do such modifications.

If such modification would be allowed, then this example would produce different outputs.

Problem

If you turn off exceptions by compiling with `-fno-exceptions` are all functions considered noexcept for example by `std::move_if_noexcept` or do you still have to declare functions noexcept for that reason?

Original source

Related problems