Debian Codegraph @

clang-tools-extra/docs/clang-tidy/checks/bugprone/pointer-arithmetic-on-polymorphic-object.rst

raw
1 .. title:: clang-tidy - bugprone-pointer-arithmetic-on-polymorphic-object
2
3 bugprone-pointer-arithmetic-on-polymorphic-object
4 =================================================
5
6 Finds pointer arithmetic performed on classes that contain a virtual function.
7
8 Pointer arithmetic on polymorphic objects where the pointer's static type is
9 different from its dynamic type is undefined behavior, as the two types could
10 have different sizes, and thus the vtable pointer could point to an
11 invalid address.
12
13 Finding pointers where the static type contains a virtual member function is a
14 good heuristic, as the pointer is likely to point to a different,
15 derived object.
16
17 Example:
18
19 .. code-block:: c++
20
21 struct Base {
22 virtual void ~Base();
23 };
24
25 struct Derived : public Base {};
26
27 void foo() {
28 Base *b = new Derived[10];
29
30 b += 1;
31 // warning: pointer arithmetic on class that declares a virtual function can
32 // result in undefined behavior if the dynamic type differs from the
33 // pointer type
34
35 delete[] static_cast<Derived*>(b);
36 }
37
38 Options
39 -------
40
41 .. option:: IgnoreInheritedVirtualFunctions
42
43 When `true`, objects that only inherit a virtual function are not checked.
44 Classes that do not declare a new virtual function are excluded
45 by default, as they make up the majority of false positives.
46 Default: `false`.
47
48 .. code-block:: c++
49
50 void bar() {
51 Base *b = new Base[10];
52 b += 1; // warning, as Base declares a virtual destructor
53
54 delete[] b;
55
56 Derived *d = new Derived[10]; // Derived overrides the destructor, and
57 // declares no other virtual functions
58 d += 1; // warning only if IgnoreVirtualDeclarationsOnly is set to false
59
60 delete[] d;
61 }
62
63 References
64 ----------
65
66 This check corresponds to the SEI Cert rule
67 `CTR56-CPP. Do not use pointer arithmetic on polymorphic objects
68 <https://wiki.sei.cmu.edu/confluence/display/cplusplus/CTR56-CPP.+Do+not+use+pointer+arithmetic+on+polymorphic+objects>`_.