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?
If any functions called between the one that throws an exception and the one that handles the exception are specified as noexcept , noexcept(true) (or throw() in /std:c++17 mode), the program is terminated when the noexcept function propagates the exception.
Explicit instantiations may use the noexcept specifier, but it is not required. If used, the exception specification must be the same as for all other declarations.
The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. It can be used within a function template's noexcept specifier to declare that the function will throw exceptions for some types but not others.
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.
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