Qt-RangeLoopDetach

Do not use range-based for loops with non-const range-expression on Qt containers

Required inputs: IR

Iterating over a non-const Qt Copy-On-Write (COW) container using a range-based for loop detaches it. If the loop's range declaration is non-reference or const lvalue reference, the detached container's elements will not be modified, rendering the detachment superfluous. If modification of the contained elements is intended, a non-const lvalue reference range declaration can be used. This rule will not warn in that case.

Fix it by marking the container const, or, since Qt 5.7, use qAsConst():

Example

for (auto i : qAsConst(list)) { ... }

This rule is based on clazy rule range-loop-detach

Possible Messages

Key

Text

Severity

Disabled

range_loop_detach

Range-based for loop might detach Qt container of type {}.

None

False

Options

level

level : int = 1

Importance level of the rule as given for clazy. 0 is most desirable, higher values fall off in quality.