C and C++


LANG.LAMBDA.CAPTURE : Implicit Lambda Capture

Summary

A variable with automatic storage duration is implicitly captured in a lambda expression.

Properties

Class Name Implicit Lambda Capture
Significance style
Mnemonic LANG.LAMBDA.CAPTURE
Categories
AUTOSARC++14 AUTOSARC++14:A5-1-2 Variables shall not be implicitly captured in a lambda expression.
MisraC++2023 MisraC++2023:8.1.2 Variables should be captured explicitly in a non-transient lambda
Availability Available for C and C++.
Enabling Checks for this warning class are disabled by default, and require the unnormalized C ASTs for the project. To enable them, add the following WARNING_FILTER rule and RETAIN_UNNORMALIZED_C_AST specification to the project configuration file.
RETAIN_UNNORMALIZED_C_AST = Yes
WARNING_FILTER += allow class="Implicit Lambda Capture"
Note that retaining the unnormalized ASTs will increase the disk space used to store the project representation, and may make the analysis take longer.

Example

int lambdacapture(int i){
    int x = 5;
    static int y = 6;

    auto lambda_explicit = [&x](int a)->int{
               return a + x;                             // ok: x is captured explicitly
              };

    auto lambda_implicit = [&](int a)->int{
               int tmp;
               tmp = a + x;       // 'Implicit Lambda Capture' warning issued here
               tmp += a + y;                             // ok: y has non-automatic storage duration
               return tmp;
              };

    return lambda_explicit(i) + lambda_implicit(i);
}

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.