AutosarC++17_03-A5.1.4

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

Required inputs: IR

Rationale

When an object is captured by reference in a lambda, lifetime of the object is not tied to the lifetime of the lambda.

If a lambda object leaves the scope of one of its reference-captured object, the execution of the lambda expression results in an undefined behavior once the reference-captured object is accessed.

Example
// $Id: A5-1-4.cpp 272338 2017-03-28 08:15:01Z piotr.tanski $
#include <cstdint>
#include <functional>
std::function<std::int32_t()> f() {
std::int32_t i = 12;
return ([&i]() -> std::int32_t {
i = 100;
return i;
}); // Non-compliant
}
std::function<std::int32_t()> g() {
std::int32_t i = 12;
return ([i]() mutable -> std::int32_t { return ++i; }); // Compliant
}
void fn() {
auto lambda1 = f();
std::int32_t i = lambda1(); // Undefined behavior
auto lambda2 = g();
i = lambda2(); // lambda2() returns 13
}
See Also
  • SEI CERT C++ [9]: EXP61-CPP. A lambda object must not outlive any of its reference captured objects.

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.