I am passing a lambda with an init-captured loop counter like this:
#include <iostream>
auto sq(int c, int x) { return c * x * x; }
struct S {
template<class Fun>
void for_each(Fun fun) const {
for (auto i = 1; i < 4; ++i) {
fun(i);
}
}
};
int main()
{
S s;
auto sum = 0;
s.for_each([&, i = 2](auto c) mutable {
sum += sq(c, i++);
});
std::cout << sum; // 70 = 1 * 4 + 2 * 9 + 3 * 16
}
For g++ up to 7.0 SVN and for clang++ up to 3.9.1, this all compiles warning-free. However, for clang++ 5.0 SVN, I get
prog.cc:18:20: warning: lambda capture 'i' is not required to be captured for this use [-Wunused-lambda-capture] s.for_each([&, i = 2](auto c) mutable {
even though it still prints out the correct answer. Live Example
Question: why am I getting this new Wunused-lambda-capture
warning from clang?
Captures default to const value. By default, variables are captured by const value . This means when the lambda is created, the lambda captures a constant copy of the outer scope variable, which means that the lambda is not allowed to modify them.
The capture list defines the outside variables that are accessible from within the lambda function body. The only capture defaults are. & (implicitly capture the used automatic variables by reference) and. = (implicitly capture the used automatic variables by copy).
Capture clause A lambda can introduce new variables in its body (in C++14), and it can also access, or capture, variables from the surrounding scope. A lambda begins with the capture clause. It specifies which variables are captured, and whether the capture is by value or by reference.
Your code is valid.
Clang's warning is nonsense.
Report this as a bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With