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

前端 未结 2 1857
傲寒
傲寒 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 01:08

    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)!

提交回复
热议问题