GCC 严格溢出
GCC strict-overflow
我们最近为大型代码库启用了 -Wstrict-overflow=5
,并试图了解启用优化时的 ~500 条警告。有些似乎是合法的,但还有这样的事情:
std::vector<std::string> files;
...
void Add (const std::string file)
{
if (std::find(files.begin(), files.end(), file) == files.end())
{
files.push_back(file);
}
}
产生警告:
example.cc: In member function ‘void Add(std::string)’:
example.cc:465:8: error: assuming signed overflow does not occur when changing X +- C1 cmp C2 to X cmp C2 -+ C1 [-Werror=strict-overflow]
void Add (const std::string file)
^
我假设比较在 std::find()
中,并通过内联 Add()
函数公开。
我该如何解决这个问题?
是的,我已经阅读了其他 SO 问题,但没什么帮助:
23020208 std::find
std::set
。答:GCC bug,关闭警告
18521501 重构条件
22798709 有符号整数的边缘情况
How am I supposed to fix this?
由于它们是由您无法控制的事物(即 gcc)引起的误报,您需要对其进行调整:
- 一个一个地看(这就是为什么你首先启用它们,以检测可能发生溢出的地方,对吗?)
- 对于编译器正确的地方,应用更正
- 对于误报的地方,使用 #pragma 在本地禁用警告 - #pragma 的存在将意味着:"Due dilligence paid, I checked and there's no way something may overflow here".
(serenity prayer 可能有帮助)
我们最近为大型代码库启用了 -Wstrict-overflow=5
,并试图了解启用优化时的 ~500 条警告。有些似乎是合法的,但还有这样的事情:
std::vector<std::string> files;
...
void Add (const std::string file)
{
if (std::find(files.begin(), files.end(), file) == files.end())
{
files.push_back(file);
}
}
产生警告:
example.cc: In member function ‘void Add(std::string)’:
example.cc:465:8: error: assuming signed overflow does not occur when changing X +- C1 cmp C2 to X cmp C2 -+ C1 [-Werror=strict-overflow]
void Add (const std::string file)
^
我假设比较在 std::find()
中,并通过内联 Add()
函数公开。
我该如何解决这个问题?
是的,我已经阅读了其他 SO 问题,但没什么帮助:
23020208 std::find
std::set
。答:GCC bug,关闭警告
18521501 重构条件
22798709 有符号整数的边缘情况
How am I supposed to fix this?
由于它们是由您无法控制的事物(即 gcc)引起的误报,您需要对其进行调整:
- 一个一个地看(这就是为什么你首先启用它们,以检测可能发生溢出的地方,对吗?)
- 对于编译器正确的地方,应用更正
- 对于误报的地方,使用 #pragma 在本地禁用警告 - #pragma 的存在将意味着:"Due dilligence paid, I checked and there's no way something may overflow here".
(serenity prayer 可能有帮助)