Why does this code run incorrectly ? See the function "f1". It assigns the "t" to std::function. I list 3 ways to do that. But the first one is error.It will output incorrect value. If the code is complicated, the program may even crash. I have already knew the reason is that lambda "t" is a local variable so that we must capture it by value. But such code can be compiled without errors or warnings, is there a way(any compile option?) to find such error when compiling?
#include <iostream>
#include<functional>
struct aa
{
int a = 2000;
void f()
{
++a;
printf("data = %d\n", a);
}
};
std::function<void()> gf;
template<typename T>
void f1(T t)
{
1 //gf = [&] {t(); };
2 //gf = [=] {t(); };
3 //gf=t;
}
int main(int argc, char** argv)
{
aa b2;
f1([&] {b2.f(); });
gf();
return 0;
}
online test: https://godbolt.org/z/5bqGeof58
update: Latest clang can detect very simple case, but don't work for code above. example:
auto f(int a)
{
return [&]{return a;}; //warning: address of stack memory associated with parameter 'a' returned [-Wreturn-stack-address]
}
int main(int argc, char** argv)
{
printf("%d\n",f(300)());
return 0;
}