GCC错误:如果知道正常返回

时间:2017-01-18 06:21:08

标签: c++ gcc compiler-warnings pure-function

鉴于此代码:

#include <cstdlib>

void func(int x)
{
  if (x)
    abort();
};

g++ -Werror=suggest-attribute=pure抱怨:

  

错误:如果已知正常返回

,则函数可能是属性'pure'的候选对象

这对我来说似乎很奇怪 - 显然这个函数不知道正常返回是不是很明显?有没有办法告诉海湾合作委员会它不会总是正常返回,或者我不希望这个警告出现在这个特定的功能上?

演示:https://godbolt.org/g/720VOT

1 个答案:

答案 0 :(得分:1)

这似乎是gcc中的一个错误(或者至少是文档和实际实现的差异)。 documentation on -Wsuggest-attribute=pure读取:

  

<强> -Wsuggest-attribute=pure
  的 -Wsuggest-attribute=const
  的 -Wsuggest-attribute=noreturn

     

警告可能是属性pure的候选函数,   constnoreturn。编译器仅警告可见的功能   在其他编译单元中(如果是pureconst)   无法证明函数正常返回。 函数返回   通常,如果它不包含无限循环或异常返回   投掷,打电话abort或诱捕。此分析需要选项   -fipa-pure-const,默认情况下在-O及更高版本启用。   更高的优化级别可提高分析的准确性。

然而,实际分析似乎忽略了非返回调用的可能性,尽管它尊重可能的异常:

$ cat test-noreturn.cpp 
[[noreturn]] void foo();

void func(int x)
{
    if (x)
        foo();
}

$ g++ -std=c++11 -c -O -Wsuggest-attribute=pure test-noreturn.cpp 
$ cat test-noreturn-nothrow.cpp 
[[noreturn]] void foo() throw();
//                      ^^^^^^^

void func(int x)
{
    if (x)
        foo();
}
$ g++ -std=c++11 -c -O -Wsuggest-attribute=pure test-noreturn-nothrow.cpp 
test-noreturn-nothrow.cpp: In function ‘void func(int)’:
test-noreturn-nothrow.cpp:4:6: warning: function might be candidate for attribute ‘pure’ if it is known to return normally [-Wsuggest-attribute=pure]
 void func(int x)
      ^