Using pointer conversions to store/cast values: Am I breaking the strict aliasing rule?

前端 未结 2 1867
傲寒
傲寒 2020-12-12 00:35

The question relates to this post.

Some authoritative users stated that the following code breaks strict aliasing rules.

#include 

        
2条回答
  •  执念已碎
    2020-12-12 00:55

    *((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).

提交回复
热议问题