I have a class that I use to reinterpret data, but the underlying data is of the same type and yet doing this seems to violate strict aliasing. I would like to be able to reinterpret_cast to choose how to interpret the data. Here's an example:
#include <iostream>
#include <cstdlib>
template <int M>
struct mul {
int i[10];
void multiply(int idx) {
std::cout << i[idx] * M << std::endl;
}
};
void f(mul<1> &s, mul<2> &t) { int i = s.i[0]; t.i[0]++; if (s.i[0] == i) std::abort(); }
int main() {
mul<1> s;
f(s, reinterpret_cast<mul<2> &>(s));
}
The abort shows that this violates strict aliasing even though the basic type is int*. Is there a reason why this should violate strict aliasing? Is there another solution to this style problem - this is a simplified case, imagine a much more complex set of functions and reinterpretations of data using a reinterpret_cast.
I use these reinterpreted types for passing into templatized functions.
Command:
g++-8 -O3 -g test.cpp -o test
Output:
Abort trap: 6
g++-8 --version:
g++-8 (Homebrew GCC HEAD-252870) 8.0.0 20170916 (experimental) Copyright (C) 2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.