简体   繁体   中英

GCC error: function might be candidate for attribute ‘pure’ if it is known to return normally

Given this code:

#include <cstdlib>

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

g++ -Werror=suggest-attribute=pure complains:

error: function might be candidate for attribute 'pure' if it is known to return normally

This seems strange to me--isn't it plainly obvious that the function is not known to return normally? Is there any way to tell GCC that it doesn't always return normally, or that I don't want this warning to appear for this particular function?

Demo: https://godbolt.org/g/720VOT

This seems like a bug in gcc (or at least discrepancy of the documentation and actual implementation). The documentation on -Wsuggest-attribute=pure reads:

-Wsuggest-attribute=pure
-Wsuggest-attribute=const
-Wsuggest-attribute=noreturn

Warn about functions that might be candidates for attributes pure , const or noreturn . The compiler only warns for functions visible in other compilation units or (in the case of pure and const ) if it cannot prove that the function returns normally. A function returns normally if it doesn't contain an infinite loop or return abnormally by throwing, calling abort or trapping . This analysis requires option -fipa-pure-const , which is enabled by default at -O and higher. Higher optimization levels improve the accuracy of the analysis.

However, the actual analysis seems to ignore the possibility of non-returning calls, though it respects possible exceptions:

$ 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)
      ^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM