[clang-tools-extra] [clang-tidy] Improve documentation of bugprone-pointer-arithmetic-on-polymorphic-object (PR #108324)

Mainak Sil via cfe-commits cfe-commits at lists.llvm.org
Thu Sep 12 06:50:07 PDT 2024


https://github.com/MainakSil updated https://github.com/llvm/llvm-project/pull/108324

>From edb6664fbdafb5127d141fde633779865a90dde1 Mon Sep 17 00:00:00 2001
From: Mainak Sil <mainaksil0 at gmail.com>
Date: Thu, 12 Sep 2024 08:58:15 +0530
Subject: [PATCH] Improve documentation for
 bugprone-pointer-arithmetic-on-polymorphic-object

---
 ...inter-arithmetic-on-polymorphic-object.rst | 38 ++++++++++++++-----
 1 file changed, 28 insertions(+), 10 deletions(-)

diff --git a/clang-tools-extra/docs/clang-tidy/checks/bugprone/pointer-arithmetic-on-polymorphic-object.rst b/clang-tools-extra/docs/clang-tidy/checks/bugprone/pointer-arithmetic-on-polymorphic-object.rst
index 1884acd5f12b3e..4f926808f9e408 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/bugprone/pointer-arithmetic-on-polymorphic-object.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/pointer-arithmetic-on-polymorphic-object.rst
@@ -19,20 +19,33 @@ Example:
 .. code-block:: c++
 
   struct Base {
-    virtual void ~Base();
+  virtual ~Base();
+  int i;
   };
 
   struct Derived : public Base {};
 
   void foo() {
-    Base *b = new Derived[10];
+  Base *b = new Derived[10];
 
-    b += 1;
-    // warning: pointer arithmetic on class that declares a virtual function can
-    // result in undefined behavior if the dynamic type differs from the
-    // pointer type
+  b += 1;
+  // warning: pointer arithmetic on class that declares a virtual function can
+  // result in undefined behavior if the dynamic type differs from the
+  // pointer type
 
-    delete[] static_cast<Derived*>(b);
+  delete[] static_cast<Derived*>(b);
+  }
+
+  // Another example showing array access with polymorphic objects.
+  int bar(const Derived d[]) {
+    return d[1].i; // warning due to pointer arithmetic on polymorphic object
+  }
+
+  // Making Derived final suppresses the warning
+  struct FinalDerived final : public Base {};
+
+  int baz(const FinalDerived d[]) {
+    return d[1].i; // no warning as FinalDerived is final
   }
 
 Options
@@ -50,14 +63,19 @@ Options
     void bar() {
       Base *b = new Base[10];
       b += 1; // warning, as Base declares a virtual destructor
-  
+
       delete[] b;
-  
+
       Derived *d = new Derived[10]; // Derived overrides the destructor, and
                                     // declares no other virtual functions
       d += 1; // warning only if IgnoreVirtualDeclarationsOnly is set to false
-  
+
       delete[] d;
+
+      FinalDerived *f = new FinalDerived[10];
+      f += 1; // no warning, FinalDerived is final and cannot be further derived
+
+      delete[] f;
     }
 
 References



More information about the cfe-commits mailing list