问题
Recently in my code I have been explicitly writing noexcept(false)
on functions that I know do throw exceptions, mainly for people reading the code. However, I am wondering if this affects the behavior of my code or the way the compiler interprets it. Does it make any difference?
Note: I am aware that destructors are implicitly noexcept and that you have to specify noexcept(false)
to change that, I am wondering about other functions.
回答1:
Having no exception-specifier and explicitly stating noexcept(false)
are equivalent, see §15.4/12:
A function with no exception-specification or with an exception-specification of the form
noexcept(constant-expression)
where the constant-expression yieldsfalse
allows all exceptions.
So the compiler should not distinguish between them when considering exceptions.
More importantly, there's no need for you to be tacking on noexcept(false)
to your functions. As a C++ developer, you should assume every function throws by default (which is why the standard takes this stance), so you're adding no new information by writing it out; it's a waste of time for everyone.
Rather, do mark the special case where a function definitely does not throw with noexcept
, and do mark the cases where a function may throw depending on some condition with noexcept(condition)
.
If your function is purposefully the source of some exception E
, write that in your documentation.
回答2:
In his book More Exceptional C++, Herb Sutter has the following snippet (pp. 130):
The right answer to the Example 19-1 is much simpler:
// Example 19-4: The right solution // T::~T() /* throw() */ { // ... code that won't throw ... }
Example 19-4 demonstrates how to make a design decision instead of waffling.
Note that the
throw()
throws-nothing exception specification is only a comment. That's the style I've chosen to follow, in part because it turns out that exception specifications confer a lot less benefit than they're worth. Whether or not you decide to actually write the specification is a matter of taste.
(emphasis mine)
So, I feel I must point out that one of the leading experts in C++ exception-safe code seems to be against the whole concept of adding exception specifications for the compiler to use (but still leaving it in the code for the programmers to understand).
Just thought it may be interesting info...
来源:https://stackoverflow.com/questions/16244313/does-adding-noexceptfalse-benefit-the-code-in-any-way