MISRA C++:2023 Rule 8.1.2
Description
Rule Definition
Variables should be captured explicitly in a non-transient lambda.
Rationale
A lambda is nontransient if any of these conditions are true:
The lambda is invoked anywhere other than immediately after its definition.
The lambda is passed to a function that stores it.
If a nontransient lambda captures variables implicitly, then the
dependencies of these lambdas can be difficult to determine when they are invoked.
Consider the nontransient lambda sum
:
void foo() { int x, y, z; auto const sum = [&]() { return x + y; }; //... int val = sum(); //Noncompliant }
x
and
y
implicitly. When this lambda is invoked later in the code, it is
unclear which variables it uses to calculate val
. To avoid such
confusion, use explicit capture when defining nontransient lambdas. Explicit capture
helps identify which objects are captured and can help identify dangling pointers or
dangling references when the lambda is invoked.Polyspace Implementation
Polyspace® reports a violation of this rule if a nontransient lambda captures variables implicitly, either by value or by reference. Nontransient lambdas can include:
Lambdas that are not invoked immediately after their definition.
Lambdas that are returned by a function.
Lambdas that are passed to a function that stores it. Polyspace assumes a lambda is stored by a function if:
A lambda is passed to a function as an argument and then assigned to a container from the standard template library or to a variable.
A lambda is passed to a function defined in a different translation unit.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Expressions |
Category: Advisory |
Version History
Introduced in R2024b