GeneralPurpose-MutablePredicate¶
Non-static data members or captured values of predicate function objects that are state related to this object’s identity shall not be copied
Required inputs: IR
Bad code (predicate with mutable state):
struct CountingPredicate {
mutable int count = 0;
bool operator()(int x) const {
++count; // ERROR: modifies mutable member
if (count % 2) {
return x > 0;
} else {
return x < 0;
}
}
};
std::vector<int> v{-1, 0, 1, 2};
std::find_if(v.begin(), v.end(), CountingPredicate());
// Result depends on when and how many times predicate is called
Good code (stateless predicate):
struct SimplePredicate {
bool operator()(int x) const {
return x > 0; // OK: pure function, no state modification
}
};
std::vector<int> v{-1, 0, 1, 2};
auto it = std::find_if(v.begin(), v.end(), SimplePredicate());
// Deterministic and predictable
Good code (using lambda without state):
std::vectorv{-1, 0, 1, 2}; auto it = std::find_if(v.begin(), v.end(), [](int x) { return x > 0; }); // OK: stateless lambda
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
modifies_state |
Call operator of predicate passed to {} modifies state. |
None |
False |
nonconst_op |
Call operator of predicate passed to {} is not const. |
None |
False |
Options
This rule shares the following common options: exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
This rule has no individual options.