首页 > 开发 > C++ > 正文

lambda 递归为何会crash

2017-09-11 21:32:19  来源: 网友分享

下面这段代码运行会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,程序行为也符合预期。