Exception specifications and noexcept in CPP
Looking at a typical function declaration, it is not possible to determine whether a function might throw an exception or not:
int doSomething(); // can this function throw an exception or not?
In the above example, can the doSomething
function throw an exception? It’s not clear. But the answer is important in some contexts. If doSomething
could throw an exception, then it’s not safe to call this function from a destructor, or any other place where a thrown exception is undesirable.
While comments may help enumerate whether a function throws exceptions or not (and if so, what kind of exceptions), documentation can grow stale and there is no compiler enforcement for comments.
Exception specifications are a language mechanism that was originally designed to document what kind of exceptions a function might throw as part of a function specification.
The noexcept specifier
In C++, all functions are classified as either non-throwing or potentially throwing. A non-throwing function is one that promises not to throw exceptions that are visible to the caller. A potentially throwing function may throw exceptions that are visible to the caller.
在抛出异常处理时, C++中只有两种函数类型, 一种是保证不会抛出异常, 另一种是有可能抛出异常
To define a function as non-throwing, we can use the noexcept specifier. To do so, we use the noexcept keyword in the function declaration, placed to the right of the function parameter list:
void doSomething() noexcept; // this function is specified as non-throwing
Note that noexcept doesn’t actually prevent the function from throwing exceptions or calling other functions that are potentially throwing. This is allowed so long as the noexcept function catches and handles those exceptions internally, and those exceptions do not exit the noexcept function.
noexcept 函数并不代表在函数中不允许抛出异常, 只要这个函数能够在内部捕获并处理这个异常, 并且不将这个异常返回到外部调用函数, 就是一个noexcept函数.
If an unhandled exception would exit a noexcept function, std::terminate
will be called (even if there is an exception handler that would otherwise handle such an exception somewhere up the stack). And if std::terminate
is called from inside a noexcept function, stack unwinding may or may not occur (depending on implementation and optimizations), which means your objects may or may not be destructed properly prior to termination.
标签:function,exception,函数,throwing,noexcept,exceptions,CPP,throw From: https://www.cnblogs.com/wevolf/p/18518656如果一个定义为 noexcept 的函数