为什么我会收到未使用的 lambda 捕获警告?
Why am I getting an unused lambda capture warning?
我正在传递一个带有初始捕获循环计数器的 lambda,如下所示:
#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
}
对于高达 7.0 SVN 的 g++ 和高达 3.9.1 的 clang++,这一切都可以无警告编译。但是,对于 clang++ 5.0 SVN,我得到
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 {
即使它仍然打印出正确答案。 Live Example
问题:为什么我会从 clang 收到这个新的 Wunused-lambda-capture
警告?
您的代码有效。
Clang 的警告是无稽之谈。
将此报告为错误。
我正在传递一个带有初始捕获循环计数器的 lambda,如下所示:
#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
}
对于高达 7.0 SVN 的 g++ 和高达 3.9.1 的 clang++,这一切都可以无警告编译。但是,对于 clang++ 5.0 SVN,我得到
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 {
即使它仍然打印出正确答案。 Live Example
问题:为什么我会从 clang 收到这个新的 Wunused-lambda-capture
警告?
您的代码有效。
Clang 的警告是无稽之谈。
将此报告为错误。