Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions clang/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,20 @@ Improvements to Clang's diagnostics

- Clang now diagnoses dangling references for C++20's parenthesized aggregate initialization (#101957).

- Fixed a bug where Clang would not emit ``-Wunused-private-field`` warnings when an unrelated class
defined a defaulted comparison operator (#GH116270).

.. code-block:: c++

class A {
private:
int a; // warning: private field 'a' is not used, no diagnostic previously
};

class C {
bool operator==(const C&) = default;
};

Improvements to Clang's time-trace
----------------------------------

Expand Down
11 changes: 9 additions & 2 deletions clang/lib/Sema/SemaDeclCXX.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7535,8 +7535,15 @@ void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
return;
}

if (DefKind.isComparison())
UnusedPrivateFields.clear();
if (DefKind.isComparison()) {
auto PT = FD->getParamDecl(0)->getType();
if (const CXXRecordDecl *RD =
PT.getNonReferenceType()->getAsCXXRecordDecl()) {
for (FieldDecl *Field : RD->fields()) {
UnusedPrivateFields.remove(Field);
}
}
}

if (DefKind.isSpecialMember()
? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
Expand Down
14 changes: 14 additions & 0 deletions clang/test/SemaCXX/warn-unused-private-field.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,20 @@ class FriendEqDefaultCompareOutOfClass {

bool operator==(const FriendEqDefaultCompareOutOfClass &, const FriendEqDefaultCompareOutOfClass &) = default;

class HasUnusedField {
int unused_; // expected-warning{{private field 'unused_' is not used}}
};

class FriendEqDefaultCompare {
int used;
friend auto operator==(FriendEqDefaultCompare, FriendEqDefaultCompare) -> bool = default;
};

class UnrelatedFriendEqDefaultCompare {
friend auto operator==(UnrelatedFriendEqDefaultCompare, UnrelatedFriendEqDefaultCompare) -> bool = default;
int operator<=>(const UnrelatedFriendEqDefaultCompare &) const = default;
};

#endif

class NotFullyDefined {
Expand Down
Loading