Lambda expression
ID |
c.maintainability.avoid_lambda |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Readability |
Language |
C / C++ |
Rationale
A lambda’s captured state is invisible at its call site and, for a reference capture, is only as long-lived as whatever it refers to - a lambda stored and invoked after its captured references go out of scope is a dangling-reference use-after-free. Lambdas also make it easy to grow deeply nested, hard-to-name, hard-to-unit-test blocks of logic inline. Some safety-critical and embedded coding standards forbid lambdas outright in favor of named, independently testable functions with an explicit parameter list.
The following code illustrates the pattern detected by this rule:
void f1(void) {
// FLAGGED: Lambda expression
auto l1 = [](int x) { return x + 1; };
}