Given some function called X, which calls some 10-20 other functions, member functions, etc. etc., how can I possibly know whether noexcept can be specified as true or not for function X ? Wouldn't I theoretically have to use the noexcept operator for every one of the callables I use in function X to create a valid noexcept specifier for function X ? Beause of this I really do not "get" the usefulness of the noexcept specifier for any C++11 on up function at all.
2 Answers
noexcept
does not mean that you will only call functions that themselves are noexcept
or at least you call them in such a way that they won't throw. nexcept
means that the function will emit "no exceptions". You can do whatever you want within the function.
As such, you can apply noexcept
to any function, regardless of what it does internally. It's just that, if you do something that causes an exception to attempt to escape the function, std::terminate
will be called.
You therefore apply the noexcept
qualifier when you want it to be true. Or more specifically, when you have reason to believe that some piece of code will inspect the function and do something based on its exception status.

- 449,505
- 63
- 781
- 982
-
So 'noexcept' ( or 'noexcept(true)' ) means that the function code itself will not throw, as opposed to some function call within the function throwing. I wish the explanations of 'noexcept' I had read had explained it to me in that way. Thanks for the clarification ! – Edward Diener Dec 10 '19 at 19:23
The compiler won't usually dig too deep into every possible code path to verify nothing will could possibly throw, but it may issue an error if it obviously can. for example, explicitly declaring a throw
statement within the function body should be a red flag.
A big difference is what happens when the stack unwinds all the way up to a noexcept
function after an exception has been thrown from within. The program will not continue to propagate up the call stack and will instead call std::terminate()
. Depending on what kind of cleanup or error handling you believe is necessary, this may or may not be acceptable.
There are also some instances where the compiler sees this as an opportunity to make the code more efficient.
It's something you have to carefully consider to get any use out of it. I use it in my shutdown functions as a reminder that it should be safe to call in destructors and other cleanup functions. The onus is on me to make sure this truly is the case.

- 95
- 9
-
"*A big difference is what happens when the stack unwinds all the way up to a noexcept function after an exception has been thrown from within.*" This is incorrect; whether the stack is unwound is implementation-defined. – Nicol Bolas Dec 10 '19 at 03:48