下面这段代码运行会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
就可能是不完整的。如果一定要连
fun
也拷贝(按值捕获),可以采用delay的方式:这样既无warning,程序行为也符合预期。