下面这段代码运行会crash
#include <iostream>#include <windows.h>int main() { std::function<void()> fun = [=]{ std::cout << "AAA" << std::endl; Sleep(1000); fun(); }; fun(); return 0;}
复制代码
把[=]改成[&] 就能通过了
#include <iostream>#include <windows.h>int main() { std::function<void()> fun = [&]{ std::cout << "AAA" << std::endl; Sleep(1000); fun(); }; fun(); return 0;}
复制代码
而我的函数需要用[=]方式,为啥会crash呢
解决方案
fun
要先构造再调用,但是由于是值拷贝,所以在fun
构造的时候拷贝的那个fun
就可能是不完整的。
warning: variable 'fun' is uninitialized when used within its own initialization [-Wuninitialized] fun(); ^~~
如果一定要连fun
也拷贝(按值捕获),可以采用delay的方式:
#include <iostream>#include <windows.h>int main() { std::function<void()> fun = [=, &fun]{ std::function<void()> delayFun = [&]{ std::function<void()> funCopy = fun; funCopy(); }; std::cout << "AAA" << std::endl; Sleep(1000); delayFun(); }; fun(); return 0;}
这样既无warning,程序行为也符合预期。