我刚刚使用C++ 11/14 std :: thread对象编写了一个线程池,并使用worker队列中的任务。在lambda表达式中调用递归函数时遇到了一些奇怪的行为。在std :: function中调用递归函数
#include <functional>
#include <vector>
std::size_t fac(std::size_t x) {
// This will crash (segfault).
// if (x == 1) return 1;
// else return fac(x-1)*x;
// This, however, works fine.
auto res = 1;
for (auto i = 2; i < x; ++i) {
res *= x;
}
return res;
}
int main() {
std::vector<std::function<void()> > functions;
for (auto i = 0; i < 10; ++i) {
functions.emplace_back([i]() { fac(i); });
}
for (auto& fn : functions) {
fn();
}
return 0;
}
它,然而,做工精细与上面的迭代版本:如果你在一个递归的方式(包括铿锵3.5和gcc 4.9)实现fac()
下面的代码崩溃。我错过了什么?
,而您的最终状态是'X == 1'是不是因为你从0开始? – Jamboree 2014-12-08 01:33:22
重申你的最后一句话,如果“正常工作”的意思是“不会崩溃”,那么你是正确的。如果它的意思是“给出正确的答案”,请参阅我的答案,为什么你可能想重新考虑这个陈述:-) – paxdiablo 2014-12-08 02:29:10