[clang] [Clang] Fix -Wunused-private-field false negative with defaulted comparison operators (PR #116871)

Chris White via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 19 12:35:54 PST 2024


https://github.com/whiteio created https://github.com/llvm/llvm-project/pull/116871

Fix -Wunused-private-field incorrectly suppressing warnings for friend defaulted comparison operators. The warning should only be suppressed when the defaulted comparison is a class member function.

Fixes #116270

>From c69426607d63b3a0cf7d839c82cde55273a5f942 Mon Sep 17 00:00:00 2001
From: Chris White <chriswhiteiodev at gmail.com>
Date: Tue, 19 Nov 2024 20:06:28 +0000
Subject: [PATCH] [Clang] Fix -Wunused-private-field false negative with
 defaulted comparison operators

Fix -Wunused-private-field suppressing warnings when defaulted comparison
operators are declared as friend functions. The warning should only be
suppressed for comparison operators that are class members.

Fixes #116270
---
 clang/lib/Sema/SemaDeclCXX.cpp                   |  2 +-
 clang/test/SemaCXX/warn-unused-private-field.cpp | 11 +++++++++++
 2 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 26041e53de5061..e115eb0a3d7e10 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7535,7 +7535,7 @@ void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
     return;
   }
 
-  if (DefKind.isComparison())
+  if (DefKind.isComparison() && isa<CXXRecordDecl>(FD->getDeclContext()))
     UnusedPrivateFields.clear();
 
   if (DefKind.isSpecialMember()
diff --git a/clang/test/SemaCXX/warn-unused-private-field.cpp b/clang/test/SemaCXX/warn-unused-private-field.cpp
index 1128eacc309d9f..bdd66807dca35f 100644
--- a/clang/test/SemaCXX/warn-unused-private-field.cpp
+++ b/clang/test/SemaCXX/warn-unused-private-field.cpp
@@ -20,6 +20,17 @@ class SpaceShipDefaultCompare {
   int operator<=>(const SpaceShipDefaultCompare &) const = default;
 };
 
+class UnusedConstPrivateField {
+ public:
+  UnusedConstPrivateField() : unused_(0) {}
+ private:
+  const int unused_; // expected-warning{{private field 'unused_' is not used}}
+};
+
+class FriendEqDefaultCompare {
+  friend auto operator==(FriendEqDefaultCompare, FriendEqDefaultCompare) -> bool = default;
+};
+
 #endif
 
 class NotFullyDefined {



More information about the cfe-commits mailing list