[clang-tools-extra] [clang-tidy] performance-unnecessary-copy-initialization: Enhance the check for the scenario with MemberExpr initialization. (PR #151936)

Baranov Victor via cfe-commits cfe-commits at lists.llvm.org
Wed Aug 20 07:56:57 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),
----------------
vbvictor wrote:

What if in `y_ref = const_var.x.y`, variable `x` is-non const so for compiler the code look like this:
```cpp
auto tmp = const_var.x;
auto y_ref = tmp.y;
```
`y_ref` is constructed from non-const object `tmp.y` so it could not be `const auto&`, but if we write `auto y_ref = const_var.x.y` then everything is OK.

I guess we need to check const-ness of the whole chain, or not?

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


More information about the cfe-commits mailing list