[clang-tidy] Add a check to replace `memcpy`-based bit reinterpretation with `std::bit_cast`
- Dominant language
- LLVM
- Stars
- 40.5k
- Forks
- 18.7k
- PR merge metrics
- PR metrics pending
Description
It would be useful to have a clang-tidy check that recognizes the common “safe type punning via `memcpy`” pattern and suggests `std::bit_cast` in C++20 and later.
For example, code like this:
```cpp
float src = 1.0f;
uint32_t dst;
static_assert(sizeof(float) == sizeof(uint32_t));
std::memcpy(&dst, &src, sizeof(src));
```
could be rewritten as:
```cpp
auto dst = std::bit_cast(src);
```
This is clearer, shorter, and directly expresses the intent.
The check should be conservative. It should only trigger when the `memcpy` is copying the full object representation of one trivially copyable object into another trivially copyable object of the same size, and where the code is clearly doing value reinterpretation rather than buffer manipulation.
It should avoid cases involving pointers, partial copies, arrays, raw storage, serialization-style code, volatile objects, or anything else where `memcpy` is serving a broader purpose and a `bit_cast` rewrite might be misleading or wrong.
This feels like a good fit for a modernize-style check, since the original code is often already correct, just more verbose and easier to get wrong than `std::bit_cast`.
Contributor guide
Assessment
This issue has not been assessed yet.