Strict aliasing rules broken with templates and inheritance
Asked Answered
A

1

9

The following code gives me warning in gcc that I break strict aliasing rules:

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();
}

warning: dereferencing type-punned pointer will >break strict-aliasing rules [-Wstrict-aliasing] field = copy.field;

When I remove the template, is seems to compile just fine.

struct Base {
  int field = 2;
};

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

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

Am I really breaking strict aliasing rules or is it GCC producing a false positive?

I'm using -Wstrict-aliasing=3 -O3 on GCC8

Antrim answered 13/12, 2018 at 15:44 Comment(4)
Can't reproduce: gcc.godbolt.org/z/NJb4FuOratorio
@Oratorio make sure to throw -O3 to compiler args - otherwise analyzer doesn't do much.Nisan
@Nisan Huh, I see. OP, make sure to mention all your flags next time.Oratorio
Thanks @HolyBlackCat, doneAntrim
N
4

Nope, there is no strict aliasing rule violation in the provided code. It looks like a bug in gcc.

You can submit a bugreport to gcc (I was not able to find anything already there related to the snippet provided), however, judging by life and times of https://gcc.gnu.org/bugzilla/show_bug.cgi?id=41874 I would not expect immediate fix.

Nisan answered 13/12, 2018 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.