[clang-tools-extra] [clang-tidy] performance-unnecessary-copy-initialization: Enhance the check for the scenario with MemberExpr initialization. (PR #151936)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Aug 22 19:55:28 PDT 2025
================
@@ -273,6 +273,18 @@ void UnnecessaryCopyInitialization::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(LocalVarCopiedFrom(declRefExpr(
to(varDecl(hasLocalStorage()).bind(OldVarDeclId)))),
this);
+
+ auto DeclRefToConstVar =
+ declRefExpr(to(varDecl(anyOf(hasType(isConstQualified()),
+ hasType(references(isConstQualified()))))
+ .bind(OldVarDeclId)));
+ Finder->addMatcher(
+ LocalVarCopiedFrom(
+ memberExpr(hasObjectExpression(anyOf(hasDescendant(DeclRefToConstVar),
----------------
movie-travel-code wrote:
Good catch, vbvictor! However the current check results are reasonable, although they don't quite meet expectations🤔, pretty wierd!
```c++
struct NestedStruct {
Struct s;
const Struct& getConstRefS() const { return s; }
const Struct getConstS() const { return s; }
Struct getS() const { return s; }
};
const auto m1 = ns.getConstRefS().Member; // warn
const auto m2 = ns.getConstS().Member; // not warn
const auto m3 = ns.getS().Member; // not warn
```
I suspect that another matcher is at work, but these checks are currently mixed together. I will analyze the reasons next week and try to give a reasonable explanation.
```
Finder->addMatcher(
LocalVarCopiedFrom(anyOf(
isConstRefReturningFunctionCall(),
isRefReturningMethodCallWithConstOverloads(ExcludedContainerTypes))),
this);
```
btw, I added more tests to analyze these behaviors.
https://github.com/llvm/llvm-project/pull/151936
More information about the cfe-commits
mailing list