AutosarC++18_10-A5.1.2

Variables shall not be implicitly captured in a lambda expression

Required inputs: IR

Rationale

Capturing variables explicitly helps document the intention of the author. It also allows for different variables to be explicitly captured by copy or by reference within the lambda definition.

Exceptions

It is allowed to implicitly capture variables with non-automatic storage duration.

Example
// $Id: A5-1-2.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
    #include <algorithm>
    #include <cstdint>
    #include <vector>
    void Fn1(const std::vector<std::int32_t>& v)
    {
        std::uint64_t sum = 0;
        std::for_each(v.begin(), v.end(), [&](std::int32_t lhs) {
            sum += lhs;
        }); // Non-compliant

        sum = 0;
        std::for_each(v.begin(), v.end(), [&sum](std::int32_t lhs) {
            sum += lhs;
        }); // Compliant
    }
    void Fn2()
    {
        constexpr std::uint8_t n = 10;
        static std::int32_t j = 0;
        [n]() {
            std::int32_t array[n]; // Compliant
            j += 1;                 // Compliant by exception
        };
    }
See Also
  • HIC++ v4.0 [9]: 5.1.4 Do not capture variables implicitly in a lambda.
  • C++ Core Guidelines [11]: F.54: If you capture this, capture all variables explicitly (no default capture).

Possible Messages

Key

Text

Severity

Disabled

implicit_lambda_capture

Variables shall not be implicitly captured in a lambda expression.

None

False

Options

immediately_invoking_function_names

immediately_invoking_function_names : set[bauhaus.analysis.config.QualifiedName] = {'std::find_if', 'std::find_if_not', 'std::invoke'}

Names of functions that immediately invoke lambda arguments.
 

report_non_transient_lambda

report_non_transient_lambda : bool = False

Whether report implicitly passing arguments to non-transient lambda functions.
 

report_non_transient_lambda_capturing_this

report_non_transient_lambda_capturing_this : bool = False

Whether to report implicitly passing this to non-transient lambda functions.