在声明函数时,您可以使用noexcept
说明符来声明该函数不会抛出:
int foo() noexcept
{
return 10;
}
但是,如何确定函数何时抛出异常?我知道使用 new
运算符可能会抛出 std::bad_alloc
,但还有哪些其他表达式/运算符会抛出?有没有办法明确确定它是否会?
最佳答案
but what are some other expressions/operators that can throw?
潜在抛出表达式定义为(根据 cppreference )
An expression e is potentially-throwing if:
- e is a function call to a potentially-throwing function or pointer to function
- e makes an implicit call to a potentially-throwing function (such as an overloaded operator, an allocation function in a new-expression, a constructor for a function argument, or a destructor if e is a full-expression)
- e is a throw-expression
- e is a dynamic_cast that casts a polymorphic reference type
- e is a typeid expression applied to a dereferenced pointer to a polymorphic type
- e has an immediate subexpression that is potentially-throwing
此外,任何具有未定义行为的表达式。
就语言而言,未声明 noexcept
的函数可能会抛出,即使它可能永远不会抛出。
Is there a way to explicitly determine if it will?
通常不会,您无法确定表达式是否会抛出 - 至少在假设 P ≠ NP 的多项式时间内不会。
但是,您可以使用noexcept
-expression 确定一个表达式是否潜在抛出:
void foo() noexcept;
void bar() {
// nothing that might throw
}
std::cout << noexcept(1+1); // prints 1
std::cout << noexcept(foo()) // prints 1
std::cout << noexcept(bar()) // prints 0
std::cout << noexcept(new char); // prints 0
std::cout << noexcept(throw 1); // prints 0
关于c++ - 如何知道函数何时抛出异常以及何时使用 noexcept,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51562083/