MISRA C++:2023 Rule 8.1.1
Description
Rule Definition
A non-transient lambda shall not implicitly capture
this
.
Rationale
When a lambda
attempts to implicitly capture member variables of a
class by value ([=]
) or by reference ([&]
), it
implicitly captures the this
pointer. Consider this
class:
class foo { public: int data; void func() { auto lambda1 = [ = ]() {return data;}; auto lambda2 = [ & ]() {return data;}; } };
lambda1
copies the
this
pointer to the lambda scope. The lambda expression
lambda2
captures the this
pointer by reference.
Neither of these lambda expressions copies data
or captures a
reference to data
in the scope of the lambda.Implicitly capturing the this
pointer instead of member variables
can be unexpected, and can lead to a call to the lambda after the lifetime of
this
pointer ends. Calling a lambda with an expired pointer is
undefined behavior.
A transient lambda cannot be called after the end of lifetime of the
this
pointer of its enclosing class. This rule does not apply to
transient lambdas.
To avoid undefined behavior, avoid implicit capture of the this
pointer. Instead, capture the this
pointer explicitly.
Polyspace Implementation
Polyspace® reports a violation if all of these conditions are met:
A lambda is defined within a
class
orstruct
.The lambda implicitly captures member variables by value (
[=]
) or by reference ([&]
).The lambda does not explicitly capture the
this
pointer.
Violations of this rule are not reported for transient lambdas. A lambda
is transient if it is invoked immediately following its definition or if it is passed to
a function that does not store it. For example, the lambda L1
is a
nontransient lambda and the lambda L2
is a transient
lambda.
auto L1 = [&](){/**/;} auto L2 = [&](){/**/;}() //invoked immediately
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Expressions |
Category: Required |
Version History
Introduced in R2024b