Home > Article > Backend Development > How Can You Safely Type Punning in Modern C ?
The traditional approach to type punning, as exemplified by the fast inverse square root function, involved reinterpreting the bit pattern of one type as another using low-level casts. However, this approach is fraught with pitfalls such as:
In modern C , there are several safer and more reliable mechanisms for type punning:
std::bit_cast copies the bit pattern of x into a new object of type T. It is the recommended method for type punning because it ensures:
Using std::memcpy to copy bytes between memory locations is another safe option. It is suitable when:
This technique can be used to create a new object of type T using the memory of an existing object x:
new (&x) T; return *std::launder(reinterpret_cast<T*>(&x));
It is similar to std::bit_cast but allows for modifying the memory content before casting.
std::byte represents a single byte, which can be used to reinterpret the bit pattern of other types:
return *reinterpret_cast<T*>(reinterpret_cast<std::byte*>(&x));
This method is similar to the original reinterpret_cast, but it allows for explicit control over byte ordering and alignment.
Using std::bit_cast, the fast inverse square root function can be rewritten as follows:
float fast_inverse_square_root(float number) { // Assuming sizeof(long) == sizeof(float) on target platform return std::bit_cast<float>(0x5f3759df - ( std::bit_cast<long>(number) >> 1 )); }
This version is safe, performant, and adheres to modern C best practices.
The above is the detailed content of How Can You Safely Type Punning in Modern C ?. For more information, please follow other related articles on the PHP Chinese website!