这可能吗?我不认为是,但我不知道这是标准会说的,还是实现定义的?我问是因为我想知道像这样标记一个 constexpr 函数是否安全或值得 noexcept
例如:
constexpr double to_meters(double y) noexcept? {
return y * 10;
}
constexpr double x = to_meters(y); // Clang-Tidy warns about possible exception without noexcept
最佳答案
不, float 乘法通常不会抛出 C++ 异常。
但是想一想:clang-tidy 怎么可能知道 to_meter
是否会抛出异常?在 C++ 中,每个函数都可以抛出异常,除非明确声明不抛出异常。
所以 clang-tidy 有两个选择:它可以做昂贵的(可能是不确定的)控制流分析,或者它可以简单地依靠你正确地声明 nothrow
,which it does :
Finder->addMatcher(
varDecl(anyOf(hasThreadStorageDuration(), hasStaticStorageDuration()),
unless(hasAncestor(functionDecl())),
anyOf(hasDescendant(cxxConstructExpr(hasDeclaration(
cxxConstructorDecl(unless(isNoThrow())).bind("func")))),
//^^^^^^^^^^^^^^^^^^^
hasDescendant(cxxNewExpr(hasDeclaration(
functionDecl(unless(isNoThrow())).bind("func")))),
//^^^^^^^^^^^^^^^^^^^
hasDescendant(callExpr(hasDeclaration(
functionDecl(unless(isNoThrow())).bind("func"))))))
.bind("var"),
this);
关于c++ - 浮点乘法可以在 C++ 中抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50900302/