================
@@ -0,0 +1,48 @@
+.. title:: clang-tidy - bugprone-loop-variable-copied-then-modified
+
+bugprone-loop-variable-copied-then-modified
+===========================================
+
+Detects when a loop variable is copied and then subsequently modified and
+suggests replacing with a ``const`` reference or an explicit copy.
+
+This pattern is considered bugprone because, frequently, programmers do not
+realize that they are modifying a *copy* rather than an underlying value,
+resulting in subtly erroneous code.
+
+For instance, the following code attempts to null out a value in a map, but 
only
+succeeds in 
+
+.. code-block:: c++
+
+  for (auto target : target_map) {
+    target.value = nullptr;
+  }
+
+The programmer is likely to have intended this code instead:
+
+.. code-block:: c++
+    
+  for (const auto& target : target_map) {
+    target.value = nullptr;
+  }
+
+This warning can be suppressed in one of two ways:
+  - In cases where the programmer did not intend to create a copy, they can
+    convert the loop variable to a ``const`` reference. A FixIt message will
+    provide a naive suggestion of how to achieve this, which works in most
+    cases.
+  - In cases where the intent is in fact to modify a copy, they may perform the
+    copy inside the body of the loop, and perform whatever operations they like
+    on that copy.
----------------
flowerhack wrote:

I'd argue that it is better and more readable, in most cases: based on code 
we've observed in Chromium, it's a surprisingly-common footgun for developers 
to perform a copy in the loop declaration without realizing it.  Moving that 
copy inside the body of the loop takes behavior that is *implicit* and makes it 
*explicit*, difficult-to-ignore, 
demands-the-programmer-has-thought-through-what-they're-doing, etc.  See e.g. 
https://chromium-review.googlesource.com/c/chromium/src/+/6409957 and 
https://chromium-review.googlesource.com/c/chromium/src/+/6512516 —in both 
cases it seems unlikely the bug would've gone unnoticed if they'd been forced 
to either make it a reference or make the copy explicit.

https://github.com/llvm/llvm-project/pull/157213
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to