V1047. Lifetime of the lambda is greater than lifetime of the local variable captured by reference.


The analyzer has detected a suspicious variable capture in a lambda function. The warning is issued in the following situations:

Example 1:

function lambda;
{
  auto obj = dummy<int>{ 42 };
  lambda = [&obj]() { .... };
}

The variable, which will be destroyed when execution leaves the block, is captured by reference. The lifetime of the lambda function is greater than that of the object. Consequently, calling the lambda function will lead to using the reference to the already destroyed object.

The object should apparently be captured by value:

function lambda;
{
  auto obj = dummy<int>{ 42 };
  lambda = [obj]() { .... };
}

Example 2:

function lambda;
{
  auto obj1 = dummy<int>{ 42 };
  auto obj2 = dummy<int>{ 42 };
  lambda = [&]() { .... };
}

In this example, the diagnostic finds that both variables are captured by reference and generates the warning twice – one warning per variable.

Another scenario is when a function returns a lambda that has captured a local variable by reference.

Example 3:

auto obj = dummy<int>{ 42 };
return [&obj]() { .... };

In this case, the caller will get a lambda a call to which will result in using an invalid reference.

According to Common Weakness Enumeration, potential errors found by using this diagnostic are classified as CWE-672.


Bugs Found

Checked Projects
367
Collected Errors
13 552