noexcept + throw
noexcept 有几个用法:
- 在编译期返回一个常量布尔值,评估其表达式是否会抛出异常。
- 用于标志一个函数是否能抛出异常,需要一个编译期布尔常量作为参数。
- 标志函数不会抛出异常。相当于
noexcept(true)
。
// whether foo is declared noexcept depends on if the expression
// T() will throw any exceptions
template<class T>
void foo() noexcept(noexcept(T())) {}
void bar() noexcept(true) {}
void baz() noexcept { throw 42; } // noexcept is the same as noexcept(true)
int main()
{
foo<int>(); // noexcept(noexcept(int())) => noexcept(true), so this is fine
bar(); // fine
baz(); // compiles, but at runtime this calls std::terminate
}
C++17 已经禁用 throw
的显式异常声明。(被称为 Dynamic exception specification
)