c++和strict-overflow的问题

problems with g++ and strict-overflow

本文关键字:问题 strict-overflow c++      更新时间:2023-10-16

我回到一个旧项目,发现它不再用最新的g++版本(5.2.0)编译。
我得到了一个神秘的错误:

src/combos.cpp: In member function ‘void ComboHandler::execute(uint64_t) const’
src/combos.cpp:123:6: error: assuming signed overflow does not occur when changing X +- C1 cmp C2 to X cmp C2 -+ C1 [-Werror=strict-overflow]
 void ComboHandler::execute(const uint64_t Mods) const {
      ^
src/combos.cpp:123:6: error: assuming signed overflow does not occur when changing X +- C1 cmp C2 to X cmp C2 -+ C1 [-Werror=strict-overflow]
src/combos.cpp:123:6: error: assuming signed overflow does not occur when changing X +- C1 cmp C2 to X cmp C2 -+ C1 [-Werror=strict-overflow]

通过注释掉该函数中的代码块,直到它再次编译,我跟踪到这行错误:

            tmpCont.insert(actionPair(el,tmpParams));

,其中tmpCont属于std::set<actionPair, execOrder>类型,其中execOrder为:

struct execOrder {
  bool operator() (const actionPair& i, const actionPair& j) const {
  /* keep comboObjects with identical combos */
  if((i.first->Keys==j.first->Keys) && (i.first->Mods==j.first->Mods)) return true;
  /* comboObjects match if at least one key matches */
  for(const Combo::key_type::value_type &elval: i.first->Keys)
    if(std::find(j.first->Keys.begin(),j.first->Keys.end(),elval)!=j.first->Keys.end()) {
      /* don't keep matching combos */
      return false;
    }
  return true;
}

Keysstd::vector<uint64_t>。如果我在第二个if块中替换std::find(...)语句,g++将成功编译这段代码。但是,我仍然很困惑,不知道如何解决这个问题。

我的编译器标志是

-O2 -Wall -Wextra -std=c++11 -pedantic ' sd12 -config——cflags ' -Wabi -fabi-version=0 -ffor-scope - strict-enums -fuse-cxa-atexit - wwtor -dtor-privacy -Wnoexcept -Wstrict-null-sentinel - world -style-cast - woverload -virtual - wsign - promote -Wdouble-promotion -Wformat=2 -Winit-self - wmiss -include-dirs -Wswitch-default -Wswitch-enum -Wunused-local-typedefs -Wuninitialized - strict-overflow -Wstrict-overflow=5 -Wtrampolines -Wfloat-equal -Wundef -Wshadow -Wcast-align -Wconversionwvector -operation-performance -Wno-unknown-pragmas -Wdeprecated -Wno-inline -Wno-switch-default -DDEBUG -g -Werror - pedan- errors

不管怎样,这是一个GCC bug。std::find代码是正确的,警告是错误的,或者警告是正确的,std::find实现无法正确处理所有边缘情况。这要由GCC维护者来解决。

作为一种解决方法,只对这几行关闭警告。