1 .. title:: clang-tidy - bugprone-casting-through-void
3 bugprone-casting-through-void
4 =============================
6 Detects unsafe or redundant two-step casting operations involving ``void*``,
7 which is equivalent to ``reinterpret_cast`` as per the
8 `C++ Standard <https://eel.is/c++draft/expr.reinterpret.cast#7>`_.
10 Two-step type conversions via ``void*`` are discouraged for several reasons.
12 - They obscure code and impede its understandability, complicating maintenance.
13 - These conversions bypass valuable compiler support, erasing warnings related
14 to pointer alignment. It may violate strict aliasing rule and leading to
16 - In scenarios involving multiple inheritance, ambiguity and unexpected outcomes
17 can arise due to the loss of type information, posing runtime issues.
19 In summary, avoiding two-step type conversions through ``void*`` ensures clearer code,
20 maintains essential compiler warnings, and prevents ambiguity and potential runtime
21 errors, particularly in complex inheritance scenarios. If such a cast is wanted,
22 it shall be done via ``reinterpret_cast``, to express the intent more clearly.
24 Note: it is expected that, after applying the suggested fix and using
25 ``reinterpret_cast``, the check :doc:`cppcoreguidelines-pro-type-reinterpret-cast
26 <../cppcoreguidelines/pro-type-reinterpret-cast>` will emit a warning.
27 This is intentional: ``reinterpret_cast`` is a dangerous operation that can
28 easily break the strict aliasing rules when dereferencing the casted pointer,
29 invoking Undefined Behavior. The warning is there to prompt users to carefuly
30 analyze whether the usage of ``reinterpret_cast`` is safe, in which case the
31 warning may be suppressed.
37 using IntegerPointer = int *;
40 static_cast<IntegerPointer>(static_cast<void *>(ptr)); // WRONG
41 reinterpret_cast<IntegerPointer>(reinterpret_cast<void *>(ptr)); // WRONG
42 (IntegerPointer)(void *)ptr; // WRONG
43 IntegerPointer(static_cast<void *>(ptr)); // WRONG
45 reinterpret_cast<IntegerPointer>(ptr); // OK, clearly expresses intent.
46 // NOTE: dereferencing this pointer violates
47 // the strict aliasing rules, invoking
48 // Undefined Behavior.