AutosarC++17_10-A5.1.4

A lambda expression object shall not outlive any of its reference-captured objects

Required inputs: IR

When a lambda captures variables by reference, the lambda cannot outlive those captured objects. If a lambda is stored or passed to code that outlives the captured variables, the lambda's references become dangling, causing use-after-free errors when the lambda is invoked. Always use capture-by-value or ensure the lambda is used before the captured objects are destroyed.
Bad code (lambda outlives reference-captured variable):
std::function<void()> CreateLambda() {
    int x = 42;
    return [&x]() {           // ERROR: captures x by reference
        std::cout << x;       // x is destroyed when function returns
    };                          // Returning lambda that will read destroyed x
}

void Use() {
    auto func = CreateLambda();
    func();                      // Undefined behavior: x no longer exists
}
Good code (lambda stored with value capture):
std::function<void()> CreateLambda() {
    int x = 42;
    return [x]() {              // OK: captures x by value
        std::cout << x;        // Uses copy of x
    };
}

void Use() {
    auto func = CreateLambda();
    func();                      // OK: x value is captured
}
Good code (lambda used before object destroyed):
void Use() {
    int x = 42;
    auto lambda = [&x]() {      // OK: reference capture is safe here
        std::cout << x;
    };
    lambda();                    // Called before x is destroyed
    // x destroyed here, no problem
}

Possible Messages

Key

Text

Severity

Disabled

lambda_outlives_object

Lambda expression object outlives reference-captured object ‘{}’.

None

False

Options

allow_function_reference_parameter_capture

allow_function_reference_parameter_capture : bool = False

Whether reference-capturing a reference parameter of an enclosing function scope should be accepted.
 

allow_longer_living_local

allow_longer_living_local : bool = False

Whether reference-capturing a longer-living local variable should be accepted.
 

consider_constructors_as_capturing

consider_constructors_as_capturing : bool = False

Whether passing a lambda into a constructor should be considered as capturing the lambda. If the constructed object outlives one of the reference-captured objects, a message is issued. If set to false, passing the lambda into a constructor call has no effect on the analysis.