MISRAC++2023-8.1.1 (C++ only)
In this section:
Synopsis
(Required) A non-transient lambda shall not implicitly capture this
Enabled by default
Yes
Severity/Certainty
Medium/Medium

Full description
When class member variables are used in a lambda, this must be explicitly captured.
Coding standards
This check does not correspond to any coding standard rules.
Code examples
The following code example fails the check and will give a warning:
class C
{
int val;
void f() {
// Non-compliant - val is not captured, but
// 'this' is implicitly captured
auto a = [&]() { return val; };
}
};
The following code example passes the check and will not give a warning about this issue:
class C
{
int val;
void f() {
// Compliant - 'this' explicitly captured
auto a = [this]() { return val; };
}
};