brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.9 KiB · 171e6e6 Raw
53 lines · plain
1.. title:: clang-tidy - bugprone-bitwise-pointer-cast2 3bugprone-bitwise-pointer-cast4=============================5 6Warns about code that tries to cast between pointers by means of7``std::bit_cast`` or ``memcpy``.8 9The motivation is that ``std::bit_cast`` is advertised as the safe alternative10to type punning via ``reinterpret_cast`` in modern C++. However, one should not11blindly 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 19The drop-in replacement behaves exactly the same as ``reinterpret_cast``, and20Undefined Behavior is still invoked. ``std::bit_cast`` is copying the bytes of21the input pointer, not the pointee, into an output pointer of a different type,22which may violate the strict aliasing rules. However, simply looking at the23code, it looks "safe", because it uses ``std::bit_cast`` which is advertised as24safe.25 26The solution to safe type punning is to apply ``std::bit_cast`` on value types,27not on pointer types:28 29.. code-block:: c++30 31    int x{};32    float y = std::bit_cast<float>(x);33 34This way, the bytes of the input object are copied into the output object,35which is much safer. Do note that Undefined Behavior can still occur, if there36is no value of type ``To`` corresponding to the value representation produced.37Compilers may be able to optimize this copy and generate identical assembly to38the original ``reinterpret_cast`` version.39 40Code before C++20 may backport ``std::bit_cast`` by means of ``memcpy``, or41simply call ``memcpy`` directly, which is equally problematic. This is also42detected by this check:43 44.. code-block:: c++45 46    int* x{};47    float* y{};48    std::memcpy(&y, &x, sizeof(x));49 50Alternatively, if a cast between pointers is truly wanted, ``reinterpret_cast``51should be used, to clearly convey the intent and enable warnings from compilers52and linters, which should be addressed accordingly.53