Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strict aliasing rules broken with templates and inheritance

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

like image 538
S. Kaczor Avatar asked Dec 13 '18 15:12

S. Kaczor


1 Answers

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.

like image 144
SergeyA Avatar answered Sep 18 '22 13:09

SergeyA