这更像是一个方便的问题,但我想知道是否有任何方法可以抑制警告:
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 version 8.1.0 (clang-802.0.41)
最佳答案
编译器无法判断 Exception::throwExcept()
不会返回。这里有两种解决方案。一种是告诉编译器,即
struct Exception
{
[[noreturn]] static void throwExcept(SomeType const&);
};
(clang 的 -Wmissing-noreturn
,包含在 -Weverything
中,如果可以声明上述函数,将会发出警告 [[noreturn]]
但不是)或将函数重新安排为
int foo(int i) {
if (!(i>10))
Exception::throwExcept(MyCustomException("Error: i not in the accepted range"));
return i*10;
}
关于c++ - 抑制非平凡无用的警告 "control may reach end of non-void function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44503036/