Does the getValue() member function below violate the c++ strict aliasing rule?
According to the standard, I believe setValue() violates the strict aliasing rule since double is neither an aggregate type nor the base class of IEEE754_64.
What about getValue()? Is it an undefined behavior when the data member is in bit field form as the example below?
I am using similar code in a large project. GCC -O2 and -O3 output the wrong value. And the issue is gone if I add -fno-strict-aliasing. Also, the issue is gone if I use memcpy instead of casting in getValue(). Not sure if it is an GCC bug.
#include <iostream>
#include <cstring>
using namespace std;
struct IEEE754_64
{
void setValue(double);
unsigned long long getValue();
// Data members
unsigned long long d_mantissa : 52;
long long d_exponent : 11;
unsigned long long d_sign : 1;
};
void IEEE754_64::setValue(double d)
{
(*this) = *reinterpret_cast<IEEE754_64*>(&d);
}
unsigned long long IEEE754_64::getValue()
{
return * reinterpret_cast<unsigned long long *>(this);
}
int main()
{
double b = 1.0;
IEEE754_64 d;
memcpy(&d, &b, sizeof(double));
cout<<hex<<d.getValue()<<endl;
d.setValue(1.0);
cout<<hex<<d.getValue()<<endl;
return 0;
}