【问题标题】:Strict aliasing rules broken with templates and inheritance模板和继承破坏了严格的别名规则
【发布时间】:2019-05-14 21:07:20
【问题描述】:

以下代码在 gcc 中警告我违反了严格的别名规则:

struct Base {
  int field = 2;
};

template <typename T>
struct Specialization: public Base {
  void method() {
      Specialization copy;
      field = copy.field;
  }
};

int main() {
    Specialization<int> s;
    s.method();
}

警告:取消引用 type-punned 指针将 >破坏严格别名规则 [-Wstrict-aliasing] field = copy.field;

当我删除模板时,似乎编译得很好。

struct Base {
  int field = 2;
};

struct Specialization: public Base {
  void method() {
      Specialization copy;
      field = copy.field;
  }
};

int main(){
    Specialization s;
    s.method();
}

我真的违反了严格的别名规则还是 GCC 产生了误报?

我在 GCC8 上使用 -Wstrict-aliasing=3 -O3

【问题讨论】:

  • 无法复制:gcc.godbolt.org/z/NJb4Fu
  • @HolyBlackCat 确保将 -O3 扔给编译器参数 - 否则分析器不会做太多。
  • @SergeyA 嗯,我明白了。 OP,下次一定要提到你所有的旗帜。
  • 谢谢@HolyBlackCat,完成

标签: c++ templates inheritance gcc strict-aliasing


【解决方案1】:

不,在提供的代码中没有严格的别名规则违规。它看起来像 gcc 中的一个错误。

您可以向 gcc 提交错误报告(我无法找到与所提供的 sn-p 相关的任何内容),但是,从 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=41874 的生命和时间来看,我不希望立即修复。

【讨论】:

    猜你喜欢
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2015-10-15
    • 2017-02-25
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多