The question relates to this post.
Some authoritative users stated that the following code breaks strict aliasing rules.
#include
*((U*) &data)
will violate strict aliasing if this is a reinterpret_cast
and the type U
is not permitted to alias the type T
. The permitted types appear in this list.
The rule refers to both reading and writing.
Here is a good article that explains some of the rationale behind the rules.
As noted on the main strict aliasing thread, you can use memcpy
as work around , for example:
U u;
memcpy( &u, &data, sizeof u );
return u;
and in the other function
memcpy( &data, &in, sizeof data );
Note that raw byte copies of class types are subject to some restrictions (I think the classes have to be POD, and you'd better be sure they have the same layout).
However, I am never using a pointer to write data [...]
The language in the standard is more general than this; [basic.life]/7 has:
[...] a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object [...]
In your operator=
you're using an lvalue of type T
to write to data
, and in operator U
you're using a pointer of type U
to read it; where U
and T
are unrelated and not character types this is UB.
Just use memcpy
. It's guaranteed to work, and it's efficient (try it)!