抑制非平凡无用的警告"control may reach end of non-void function"



比什么都方便,但我想知道是否有任何方法可以抑制警告:

控制可能达到非空函数的终点 [-Wreturn-type]

对于我知道代码没有问题的特定情况。我的代码库中有一些帮助程序函数用于抛出异常,以及这样的代码:

int foo(int i) {
    if (i > 10) {
        return i*10;
    }
    else {
        Exception::throwExcept(MyCustomException("Error: i not in the accepted range"));
    }
}

我知道无论如何,它要么返回,要么扔掉。因此,警告在我眼中是毫无用处的,只是编译器无法确定控制流路径实际上最终会抛出。

我仍然希望看到这个警告弹出窗口,以应对它实际上是代码错误的标志(即路径不返回或抛出

(的情况。以

便携式方式可以做到这一点吗?

编辑:忘记添加我正在使用的编译器,

Apple LLVM 版本 8.1.0 (clang-802.0.41(

编译器无法确定Exception::throwExcept()不会返回。这里有两种解决方案。一种是告诉编译器,即

struct Exception
{
    [[noreturn]] static void throwExcept(SomeType const&);
};

(包含在 -Weverything 中的 Clang -Wmissing-noreturn 将警告上述函数是否可以声明为 [[noreturn]] 但不是(或将函数重新排列为

int foo(int i) {
    if (!(i>10))
        Exception::throwExcept(MyCustomException("Error: i not in the accepted range"));
    return i*10;
}

Exception::throwExcept函数标记为[[noreturn]]应该可以帮助编译器弄清楚它实际上不会返回。

抑制错误的一种快速而肮脏的方法是在 return 语句中使用逗号运算符。 如果您使用

return Exception::throwExcept(MyCustomException("Error: i not in the accepted range")), 0;

编译器将看到一个 return 语句,但它永远不会实际执行为

Exception::throwExcept(MyCustomException("Error: i not in the accepted range"))

将在返回 0 之前抛出。

在我看来

,您的编译器无法看到内部Exception::throwExcept知道它总是抛出异常。

帮助编译器处理原始C++异常throw作为函数的最后一行:throw std::exception("Just to help the compiler know to not warn here"); 这不会损害性能,因为代码永远不会被执行。

最新更新