brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.6 KiB · 6b2a82f Raw
66 lines · plain
1.. title:: clang-tidy - bugprone-compare-pointer-to-member-virtual-function2 3bugprone-compare-pointer-to-member-virtual-function4===================================================5 6Detects unspecified behavior about equality comparison between pointer to7member virtual function and anything other than null-pointer-constant.8 9.. code-block:: c++10 11    struct A {12      void f1();13      void f2();14      virtual void f3();15      virtual void f4();16 17      void g1(int);18    };19 20    void fn() {21      bool r1 = (&A::f1 == &A::f2);  // ok22      bool r2 = (&A::f1 == &A::f3);  // bugprone23      bool r3 = (&A::f1 != &A::f3);  // bugprone24      bool r4 = (&A::f3 == nullptr); // ok25      bool r5 = (&A::f3 == &A::f4);  // bugprone26 27      void (A::*v1)() = &A::f3;28      bool r6 = (v1 == &A::f1); // bugprone29      bool r6 = (v1 == nullptr); // ok30 31      void (A::*v2)() = &A::f2;32      bool r7 = (v2 == &A::f1); // false positive, but potential risk if assigning other value to v2.33 34      void (A::*v3)(int) = &A::g1;35      bool r8 = (v3 == &A::g1); // ok, no virtual function match void(A::*)(int) signature.36    }37 38Provide warnings on equality comparisons involve pointers to member virtual39function or variables which is potential pointer to member virtual function and40any entity other than a null-pointer constant.41 42In certain compilers, virtual function addresses are not conventional pointers43but instead consist of offsets and indexes within a virtual function table44(vtable). Consequently, these pointers may vary between base and derived45classes, leading to unpredictable behavior when compared directly. This issue46becomes particularly challenging when dealing with pointers to pure virtual47functions, as they may not even have a valid address, further complicating48comparisons.49 50Instead, it is recommended to utilize the ``typeid`` operator or other51appropriate mechanisms for comparing objects to ensure robust and predictable52behavior in your codebase. By heeding this detection and adopting a more reliable53comparison method, you can mitigate potential issues related to unspecified54behavior, especially when dealing with pointers to member virtual functions or pure55virtual functions, thereby improving the overall stability and maintainability56of your code. In scenarios involving pointers to member virtual functions, it's57only advisable to employ ``nullptr`` for comparisons.58 59 60Limitations61-----------62 63Does not analyze values stored in a variable. For variable, only analyze all64virtual methods in the same ``class`` or ``struct`` and diagnose when assigning65a pointer to member virtual function to this variable is possible.66