Opinions on type-punning in C++?

后端 未结 5 453
野趣味
野趣味 2020-12-02 23:42

I\'m curious about conventions for type-punning pointers/arrays in C++. Here\'s the use case I have at the moment:

Compute a simple 32-bit checksum over a
5条回答
  •  死守一世寂寞
    2020-12-02 23:56

    As far as the C++ standard is concerned, litb's answer is completely correct and the most portable. Casting const char *data to a const uint3_t *, whether it be via a C-style cast, static_cast, or reinterpret_cast, breaks the strict aliasing rules (see Understanding Strict Aliasing). If you compile with full optimization, there's a good chance that the code will not do the right thing.

    Casting through a union (such as litb's my_reint) is probably the best solution, although it does technically violate the rule that if you write to a union through one member and read it through another, it results in undefined behavior. However, practically all compilers support this, and it results in the the expected result. If you absolutely desire to conform to the standard 100%, go with the bit-shifting method. Otherwise, I'd recommend going with casting through a union, which is likely to give you better performance.

提交回复
热议问题