Suppose i have two structs
struct B
{
int n;
};
struct C
{
int k;
};
and
B b = {};
C& c = reinterpret_cast<C&>(b); //Not Ok , compiler(gcc 8.5 with -O2 -Wall) is not happy
C *c1 = reinterpret_cast<C*>(&b); //Okay, compiler(gcc 8.5 with -O2 -Wall) is happy
sample code:
#include<new>
#include<iostream>
int main() {
struct B { int n; };
struct C
{ int k; }
;
B b = {};
C c = reinterpret_cast<C&>(b);
C *c1 = reinterpret_cast<C*>(&b);
printf("b.n is %d\n",b.n);
printf("c.k is %d\n",c.k);
printf("c1.k is %d\n",c1->k);
return 0;
}
Can somebody help me to understand why there is difference in behavior for above code though I believe they are functionally same?
I expected compiler to be happy even on references as I know both types have same memory alignment.
I get the following warning
<source>:142:29: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
C c = reinterpret_cast<C&>(b);