llvm / llvm/llvm-project

[clang-tidy] Add a check to replace `memcpy`-based bit reinterpretation with `std::bit_cast`

Open
#189,499 8 comments 0 reactions 1 assignee Claimed by @unterumarmung View on GitHub
check-request clang-tidy
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.