C++ 关于c++;lambda(具有非自动存储持续时间)
我的代码如下C++ 关于c++;lambda(具有非自动存储持续时间),c++,lambda,storage,duration,C++,Lambda,Storage,Duration,我的代码如下 #include <iostream> #include <string> using namespace std; int x; struct A { auto func() { auto test([&, &x](){cout << x << endl;}); test(); } }; int main() { A a; x = 5;
#include <iostream>
#include <string>
using namespace std;
int x;
struct A
{
auto func()
{
auto test([&, &x](){cout << x << endl;});
test();
}
};
int main()
{
A a;
x = 5;
a.func();
}
然而,我得到如下警告
#include <iostream>
#include <string>
using namespace std;
int x;
struct A
{
auto func()
{
auto test([&, &x](){cout << x << endl;});
test();
}
};
int main()
{
A a;
x = 5;
a.func();
}
ex.cpp:在成员函数“auto A::func()”中:ex.cpp:11:19:警告:捕获具有非自动存储持续时间的变量“x”
autotest([&,&x](){cout您的lambda实际上没有捕获任何内容:
x
是一个全局变量(如std::cout
)
只需删除捕获:
auto func()
{
auto test([](){ std::cout << x << std::endl; });
test();
}
auto func()
{
自动测试([]){std::cout您的lambda实际上没有捕获任何内容:
x
是一个全局变量(如std::cout
)
只需删除捕获:
auto func()
{
auto test([](){ std::cout << x << std::endl; });
test();
}
auto func()
{
自动测试([]){std::coutx
是一个全局变量,不需要捕获它。而且“捕获全部”也不需要。您实际上什么也没有捕获。x
是一个全局变量,不需要捕获它。而且“捕获全部”也不需要。您实际上什么都没有捕获。