[clang-tools-extra] [clang-tidy][NFC][docs] Add limitation of variable lifetimes in performance-unnecessary-copy-initialization (PR #151862)

Baranov Victor via cfe-commits cfe-commits at lists.llvm.org
Sun Aug 3 05:37:42 PDT 2025


https://github.com/vbvictor created https://github.com/llvm/llvm-project/pull/151862

Addresses https://github.com/llvm/llvm-project/issues/150189.

>From 9ac52ed93d36d03bd347c477edbb07c20395d6cc Mon Sep 17 00:00:00 2001
From: Victor Baranov <bar.victor.2002 at gmail.com>
Date: Sun, 3 Aug 2025 15:35:01 +0300
Subject: [PATCH] [clang-tidy][NFC][docs] Add limitation of variable lifetimes
 in performance-unnecessary-copy-initialization

---
 .../unnecessary-copy-initialization.rst       | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)

diff --git a/clang-tools-extra/docs/clang-tidy/checks/performance/unnecessary-copy-initialization.rst b/clang-tools-extra/docs/clang-tidy/checks/performance/unnecessary-copy-initialization.rst
index bb4f42c88d62f..0e9d5476e7016 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/performance/unnecessary-copy-initialization.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/performance/unnecessary-copy-initialization.rst
@@ -59,3 +59,22 @@ Options
    types that don't own the underlying data. Like for `AllowedTypes` above,
    regular expressions are accepted and the inclusion of `::` determines whether
    the qualified typename is matched or not.
+
+
+Limitations
+-----------
+
+This check does not perform lifetime analysis and may suggest replacing copies
+with const references that could become dangling. Be cautious when the
+referenced object might be invalidated by subsequent operations.
+
+.. code-block:: c++
+
+  void consume(const S&);
+
+  void func(std::vector<S> &Vec) {
+    const auto It = Vec.begin();
+    const S Value(*It); // The warning will suggest making this a const reference.
+    Vec.erase(It); // Container modifications could invalidate references.
+    consume(Value); // Safe with copy, dangling reference otherwise.
+  }



More information about the cfe-commits mailing list