Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting an unused lambda capture warning?

Tags:

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?

like image 713
TemplateRex Avatar asked Jan 31 '17 14:01

TemplateRex


People also ask

What are lambda captures?

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.

What is capture list in lambda C++?

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).

How do you capture variables in lambda?

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.


1 Answers

Your code is valid.

Clang's warning is nonsense.

Report this as a bug.

like image 61
Yakk - Adam Nevraumont Avatar answered Oct 26 '22 05:10

Yakk - Adam Nevraumont