Rule A5-1-2 (required, implementation, automated)

Variables shall not be implicitly captured in a lambda expression.

Rationale

Capturing variables explicitly helps document the intention of the author. It also allows for different variables to be explicitly captured by copy or by reference within the lambda definition.

Exception

It is allowed to implicitly capture variables with non-automatic storage duration.

Example

// $Id: A5-1-2.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <algorithm>
#include <cstdint>
#include <vector>
void Fn1(const std::vector<std::int32_t>& v)
{
std::uint64_t sum = 0;
std::for_each(v.begin(), v.end(), [&](std::int32_t lhs) {
sum += lhs;
}); // Non-compliant

sum = 0;
std::for_each(v.begin(), v.end(), [&sum](std::int32_t lhs) {
sum += lhs;
}); // Compliant
}
void Fn2()
{
constexpr std::uint8_t n = 10;
static std::int32_t j = 0;
[n]() {
std::int32_t array[n]; // Compliant
j += 1;
// Compliant by exception
};
}

See also

HIC++ v4.0 [9]: 5.1.4 Do not capture variables implicitly in a lambda. C++ Core Guidelines [11]: F.54: If you capture this, capture all variables explicitly (no default capture).