|
| 1 | +.. title:: clang-tidy - bugprone-bitwise-pointer-cast |
| 2 | + |
| 3 | +bugprone-bitwise-pointer-cast |
| 4 | +============================= |
| 5 | + |
| 6 | +Warns about code that tries to cast between pointers by means of |
| 7 | +``std::bit_cast`` or ``memcpy``. |
| 8 | + |
| 9 | +The motivation is that ``std::bit_cast`` is advertised as the safe alternative |
| 10 | +to type punning via ``reinterpret_cast`` in modern C++. However, one should not |
| 11 | +blindly replace ``reinterpret_cast`` with ``std::bit_cast``, as follows: |
| 12 | + |
| 13 | +.. code-block:: c++ |
| 14 | + |
| 15 | + int x{}; |
| 16 | + -float y = *reinterpret_cast<float*>(&x); |
| 17 | + +float y = *std::bit_cast<float*>(&x); |
| 18 | + |
| 19 | +The drop-in replacement behaves exactly the same as ``reinterpret_cast``, and |
| 20 | +Undefined Behavior is still invoked. ``std::bit_cast`` is copying the bytes of |
| 21 | +the input pointer, not the pointee, into an output pointer of a different type, |
| 22 | +which may violate the strict aliasing rules. However, simply looking at the |
| 23 | +code, it looks "safe", because it uses ``std::bit_cast`` which is advertised as |
| 24 | +safe. |
| 25 | + |
| 26 | +The solution to safe type punning is to apply ``std::bit_cast`` on value types, |
| 27 | +not on pointer types: |
| 28 | + |
| 29 | +.. code-block:: c++ |
| 30 | + |
| 31 | + int x{}; |
| 32 | + float y = std::bit_cast<float>(x); |
| 33 | + |
| 34 | +This way, the bytes of the input object are copied into the output object, which |
| 35 | +is much safer. Do note that Undefined Behavior can still occur, if there is no |
| 36 | +value of type ``To`` corresponding to the value representation produced. |
| 37 | +Compilers may be able to optimize this copy and generate identical assembly to |
| 38 | +the original ``reinterpret_cast`` version. |
| 39 | + |
| 40 | +Code before C++20 may backport ``std::bit_cast`` by means of ``memcpy``, or |
| 41 | +simply call ``memcpy`` directly, which is equally problematic. This is also |
| 42 | +detected by this check: |
| 43 | + |
| 44 | +.. code-block:: c++ |
| 45 | + |
| 46 | + int* x{}; |
| 47 | + float* y{}; |
| 48 | + std::memcpy(&y, &x, sizeof(x)); |
| 49 | + |
| 50 | +Alternatively, if a cast between pointers is truly wanted, ``reinterpret_cast`` |
| 51 | +should be used, to clearly convey the intent and enable warnings from compilers |
| 52 | +and linters, which should be addressed accordingly. |
0 commit comments