Range-for loop copies each element

ID

c.performance.for_range_copy

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Unnecessary Copy

Language

C / C++

Description

This range-based for binds each element by value, copying it on every iteration. When the loop does not modify the element, prefer for (const auto &x : c) to iterate by reference. (For trivially small element types the copy is negligible, so treat this as an advisory.)

Rationale

This range-based for binds each element by value, copying it on every iteration. When the loop does not modify the element, prefer for (const auto &x : c) to iterate by reference. (For trivially small element types the copy is negligible, so treat this as an advisory.)

The following code illustrates the pattern detected by this rule:

void f(const std::vector<std::string> &v) {
  // FLAGGED: Range-for loop copies each element
  for (auto s : v) { use(s); }

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.