首页 > 解决方案 > 浮点乘法可以在 C++ 中引发异常吗?

问题描述

这可能吗?我不认为是这样,但我不知道这是标准会说的话,还是定义了实现?我问是因为我想知道标记像这样的 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

标签: c++noexcept

解决方案


不,浮点乘法通常不会引发 C++ 异常。

但是想一想:clang-tidy 怎么可能知道是否to_meter会抛出异常呢?在 C++ 中,除非明确声明不抛出异常,否则每个函数都可以抛出异常。

所以 clang-tidy 有两个选择:它可以进行昂贵的(可能是不确定的)控制流分析,或者它可以简单地依赖于你正确声明nothrow它确实

  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);

推荐阅读