Skip to content

Commit d04c2ed

Browse files
authored
[clang-tidy] Improve documentation of bugprone-pointer-arithmetic-on-polymorphic-object (#108324)
Fix #107831.
1 parent cd774c8 commit d04c2ed

File tree

1 file changed

+14
-14
lines changed

1 file changed

+14
-14
lines changed

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

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,20 +19,28 @@ Example:
1919
.. code-block:: c++
2020

2121
struct Base {
22-
virtual void ~Base();
22+
virtual ~Base();
23+
int i;
2324
};
2425

2526
struct Derived : public Base {};
2627

27-
void foo() {
28-
Base *b = new Derived[10];
29-
28+
void foo(Base* b) {
3029
b += 1;
3130
// warning: pointer arithmetic on class that declares a virtual function can
3231
// result in undefined behavior if the dynamic type differs from the
3332
// pointer type
33+
}
34+
35+
int bar(const Derived d[]) {
36+
return d[1].i; // warning due to pointer arithmetic on polymorphic object
37+
}
3438

35-
delete[] static_cast<Derived*>(b);
39+
// Making Derived final suppresses the warning
40+
struct FinalDerived final : public Base {};
41+
42+
int baz(const FinalDerived d[]) {
43+
return d[1].i; // no warning as FinalDerived is final
3644
}
3745

3846
Options
@@ -47,17 +55,9 @@ Options
4755

4856
.. code-block:: c++
4957

50-
void bar() {
51-
Base *b = new Base[10];
58+
void bar(Base b[], Derived d[]) {
5259
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
5860
d += 1; // warning only if IgnoreVirtualDeclarationsOnly is set to false
59-
60-
delete[] d;
6161
}
6262

6363
References

0 commit comments

Comments
 (0)