69 lines · plain
1.. title:: clang-tidy - bugprone-pointer-arithmetic-on-polymorphic-object2 3bugprone-pointer-arithmetic-on-polymorphic-object4=================================================5 6Finds pointer arithmetic performed on classes that contain a virtual function.7 8Pointer arithmetic on polymorphic objects where the pointer's static type is9different from its dynamic type is undefined behavior, as the two types could10have different sizes, and thus the vtable pointer could point to an11invalid address.12 13Finding pointers where the static type contains a virtual member function is a14good heuristic, as the pointer is likely to point to a different,15derived object.16 17Example:18 19.. code-block:: c++20 21 struct Base {22 virtual ~Base();23 int i;24 };25 26 struct Derived : public Base {};27 28 void foo(Base* b) {29 b += 1;30 // warning: pointer arithmetic on class that declares a virtual function can31 // result in undefined behavior if the dynamic type differs from the32 // pointer type33 }34 35 int bar(const Derived d[]) {36 return d[1].i; // warning due to pointer arithmetic on polymorphic object37 }38 39 // Making Derived final suppresses the warning40 struct FinalDerived final : public Base {};41 42 int baz(const FinalDerived d[]) {43 return d[1].i; // no warning as FinalDerived is final44 }45 46Options47-------48 49.. option:: IgnoreInheritedVirtualFunctions50 51 When `true`, objects that only inherit a virtual function are not checked.52 Classes that do not declare a new virtual function are excluded53 by default, as they make up the majority of false positives.54 Default: `false`.55 56 .. code-block:: c++57 58 void bar(Base b[], Derived d[]) {59 b += 1; // warning, as Base declares a virtual destructor60 d += 1; // warning only if IgnoreVirtualDeclarationsOnly is set to false61 }62 63References64----------65 66This check corresponds to the SEI Cert rule67`CTR56-CPP. Do not use pointer arithmetic on polymorphic objects68<https://wiki.sei.cmu.edu/confluence/display/cplusplus/CTR56-CPP.+Do+not+use+pointer+arithmetic+on+polymorphic+objects>`_.69