[clang] [clang] When checking for covariant return types, make sure the poiners or references are to *classes* (PR #111856)

via cfe-commits cfe-commits at lists.llvm.org
Thu Oct 10 08:19:41 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: Boaz Brickner (bricknerb)

<details>
<summary>Changes</summary>

https://eel.is/c++draft/class.virtual#<!-- -->8.1

This prevents overriding methods with non class return types that have less cv-qualification.

Fixes: #<!-- -->111742 

---
Full diff: https://github.com/llvm/llvm-project/pull/111856.diff


2 Files Affected:

- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+2-2) 
- (modified) clang/test/SemaCXX/virtual-override.cpp (+10) 


``````````diff
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 9cb2ed02a3f764..6195b62b8afa16 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -18273,7 +18273,7 @@ bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
   }
 
   // The return types aren't either both pointers or references to a class type.
-  if (NewClassTy.isNull()) {
+  if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
     Diag(New->getLocation(),
          diag::err_different_return_type_for_overriding_virtual_function)
         << New->getDeclName() << NewTy << OldTy
@@ -18296,7 +18296,7 @@ bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
                               diag::err_covariant_return_incomplete,
                               New->getDeclName()))
         return true;
-    }
+      }
 
     // Check if the new class derives from the old class.
     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
diff --git a/clang/test/SemaCXX/virtual-override.cpp b/clang/test/SemaCXX/virtual-override.cpp
index 72abfc3cf51e1f..6008b8ed063f20 100644
--- a/clang/test/SemaCXX/virtual-override.cpp
+++ b/clang/test/SemaCXX/virtual-override.cpp
@@ -289,3 +289,13 @@ namespace PR8168 {
     static void foo() {} // expected-error{{'static' member function 'foo' overrides a virtual function}}
   };
 }
+
+namespace T13 {
+  struct A {
+    virtual const int *f() const; // expected-note{{overridden virtual function is here}}
+  };
+
+  struct B : A {
+    int *f() const override; // expected-error{{virtual function 'f' has a different return type ('int *') than the function it overrides (which has return type 'const int *')}}
+  };
+}

``````````

</details>


https://github.com/llvm/llvm-project/pull/111856


More information about the cfe-commits mailing list