|
| 1 | +.. title:: clang-tidy - bugprone-bit-cast-pointers |
| 2 | + |
| 3 | +bugprone-bit-cast-pointers |
| 4 | +========================== |
| 5 | + |
| 6 | +Warns about usage of ``std::bit_cast`` when the input and output types are |
| 7 | +pointers. |
| 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 are able to optimize this copy and generate identical assembly to the |
| 38 | +original ``reinterpret_cast`` version. |
| 39 | + |
| 40 | +Alternatively, if a cast between pointers is truly wanted, ``reinterpret_cast`` |
| 41 | +should be used, to clearly convey the intent and enable warnings from compilers |
| 42 | +and linters, which should be addressed accordingly. |
0 commit comments