1.. title:: clang-tidy - bugprone-compare-pointer-to-member-virtual-function 2 3bugprone-compare-pointer-to-member-virtual-function 4=================================================== 5 6Detects unspecified behavior about equality comparison between pointer to member 7virtual 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); // ok 22 bool r2 = (&A::f1 == &A::f3); // bugprone 23 bool r3 = (&A::f1 != &A::f3); // bugprone 24 bool r4 = (&A::f3 == nullptr); // ok 25 bool r5 = (&A::f3 == &A::f4); // bugprone 26 27 void (A::*v1)() = &A::f3; 28 bool r6 = (v1 == &A::f1); // bugprone 29 bool r6 = (v1 == nullptr); // ok 30 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 virtual 39function or variables which is potential pointer to member virtual function and 40any entity other than a null-pointer constant. 41 42In certain compilers, virtual function addresses are not conventional pointers 43but instead consist of offsets and indexes within a virtual function table 44(vtable). Consequently, these pointers may vary between base and derived 45classes, leading to unpredictable behavior when compared directly. This issue 46becomes particularly challenging when dealing with pointers to pure virtual 47functions, as they may not even have a valid address, further complicating 48comparisons. 49 50Instead, it is recommended to utilize the ``typeid`` operator or other appropriate 51mechanisms for comparing objects to ensure robust and predictable behavior in 52your codebase. By heeding this detection and adopting a more reliable comparison 53method, you can mitigate potential issues related to unspecified behavior, 54especially when dealing with pointers to member virtual functions or pure 55virtual functions, thereby improving the overall stability and maintainability 56of your code. In scenarios involving pointers to member virtual functions, it's 57only advisable to employ ``nullptr`` for comparisons. 58 59Limitations 60----------- 61 62Does not analyze values stored in a variable. For variable, only analyze all virtual 63methods in the same ``class`` or ``struct`` and diagnose when assigning a pointer 64to member virtual function to this variable is possible. 65