AutosarC++18_03-A5.1.4¶
A lambda expression object shall not outlive any of its reference-captured objects
Required inputs: IR
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¶
This rule shares the following common options: exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
allow_function_reference_parameter_capture¶
allow_function_reference_parameter_capture : bool = False
allow_longer_living_local¶
allow_longer_living_local : bool = False
consider_constructors_as_capturing¶
consider_constructors_as_capturing : bool = False