Why is this an issue?
std::bit_cast
is one of the standard functions working with binary representation. Together with other bit-level functions, it is
defined in the <bit>
header introduced by C++20.
std::bit_cast
standardizes the diverse and sub-optimal approaches of reinterpreting a value as being of a different type of the same
length preserving its binary representation.
Before C++20, the correct way to reinterpret a value was a call to std::memcpy
, copying the exact binary representation from a
variable of one type into a variable of another. Although canonical, the use of std::memcpy
might still be confusing, it is verbose, and
it might introduce performance overhead if the compiler does not recognize the idiom and does not remove the function call.
In contrast, std::bit_cast
clearly states the intent and is guaranteed to map to an optimal implementation.
This rule reports the uses of std::memcpy
that can be replaced by std::bit_cast
.
Noncompliant code example
static_assert(sizeof(float) == sizeof(uint32_t));
float src = 1.0f;
uint32_t dst;
std::memcpy(&dst, &src, sizeof(float)); // Noncompliant: verbose and might incur performance hit
Compliant solution
float src = 1.0f;
auto dst = std::bit_cast<uint32_t>(src); // Compliant
Resources
Other common patterns predating C++20:
- {rule:cpp:S3630} - replacing
std::reinterpret_cast
with std::bit_cast
.
- {rule:cpp:S871} - replacing C-style cast with
std::bit_cast
.