52 lines · plain
1.. title:: clang-tidy - bugprone-casting-through-void2 3bugprone-casting-through-void4=============================5 6Detects unsafe or redundant two-step casting operations involving ``void*``,7which is equivalent to ``reinterpret_cast`` as per the8`C++ Standard <https://eel.is/c++draft/expr.reinterpret.cast#7>`_.9 10Two-step type conversions via ``void*`` are discouraged for several reasons.11 12- They obscure code and impede its understandability, complicating maintenance.13- These conversions bypass valuable compiler support, erasing warnings related14 to pointer alignment. It may violate strict aliasing rule and leading to15 undefined behavior.16- In scenarios involving multiple inheritance, ambiguity and unexpected17 outcomes can arise due to the loss of type information, posing runtime18 issues.19 20In summary, avoiding two-step type conversions through ``void*`` ensures21clearer code, maintains essential compiler warnings, and prevents ambiguity22and potential runtime errors, particularly in complex inheritance scenarios.23If such a cast is wanted, it shall be done via ``reinterpret_cast``,24to express the intent more clearly.25 26Note: it is expected that, after applying the suggested fix and using27``reinterpret_cast``, the check28:doc:`cppcoreguidelines-pro-type-reinterpret-cast29<../cppcoreguidelines/pro-type-reinterpret-cast>` will emit a warning.30This is intentional: ``reinterpret_cast`` is a dangerous operation that can31easily break the strict aliasing rules when dereferencing the casted pointer,32invoking Undefined Behavior. The warning is there to prompt users to carefully33analyze whether the usage of ``reinterpret_cast`` is safe, in which case the34warning may be suppressed.35 36Examples:37 38.. code-block:: c++39 40 using IntegerPointer = int *;41 double *ptr;42 43 static_cast<IntegerPointer>(static_cast<void *>(ptr)); // WRONG44 reinterpret_cast<IntegerPointer>(reinterpret_cast<void *>(ptr)); // WRONG45 (IntegerPointer)(void *)ptr; // WRONG46 IntegerPointer(static_cast<void *>(ptr)); // WRONG47 48 reinterpret_cast<IntegerPointer>(ptr); // OK, clearly expresses intent.49 // NOTE: dereferencing this pointer violates50 // the strict aliasing rules, invoking51 // Undefined Behavior.52