为什么允许在 noexcept 标记的函数内抛出异常? [重复]

问题描述 投票:0回答:2

我很难理解这一点。

double compute(double x, double y) noexcept
{
   if (y == 0)
       throw std::domain_error("y is zero");
   return x / y;
}

这在 clang 中编译得很好(我没有检查 gcc),但对我来说这似乎毫无意义。为什么编译器允许 noexcept 函数包含 throw 语句?

c++ exception compilation tags noexcept
2个回答
19
投票

将会发生的是

std::terminate()
被触发,因为您的异常规范不允许发生这种情况(请参阅 [except.spec/9])。

至于为什么允许,根本不可能彻底检查是否有任何内容违反规范。考虑这样的事情:

double f(double );
double compute(double x, double y) noexcept
{
    return x / f(y);
} 

f
可以扔吗?不能说。


11
投票

声称不抛出异常的函数实际上可能会抛出异常。
如果

noexcept
函数 does 抛出,则调用
terminate
,从而强制承诺在运行时不抛出。

// The compiler does not check the `noexcept` specification at compile time.
void f() noexcept // Promises to not throw any exception
{
    throw runtime_error("error"); // Violates the exception specification
}

指定函数不会抛出异常,向不抛出函数的调用者承诺他们永远不需要处理异常。 要么该函数不会抛出异常,要么整个程序将终止。

© www.soinside.com 2019 - 2024. All rights reserved.