我编写了以下代码,该代码使用function<int(int)>
类型的函数。函数compose
,print
,inc
和guarded
是组合其他函数或产生一些外部效果的帮助器。然后我用它们来构建我的程序:
/* start of the program */
function<int(int)> recursion();
function<int(int)> go =
compose(guarded(10, recursion()), compose(inc, print("go")));
function<int(int)> recursion() {
return compose(go, print("recursion"));
}
但是,在调用recursion()(0)
时,第二次到达std::bad_function_call
时会抛出异常go
,但我不明白为什么。是否有任何悬空参考或空std::function
?此外,eta-expanding go
有效:
function<int(int)> go = [](int n) -> int {
return compose(guarded(10, recursion()), compose(inc, print("go")))(n);
};
原始代码有什么问题?为什么替代方案有效?
完整代码:
#include <string>
#include <iostream>
#include <functional>
using namespace std;
/* helper functions, some combinators */
//composing two functions, f1 . f2
function<int(int)> compose(const function<int(int)>& f1, const function<int(int)>& f2) {
return [f1,f2](int n) -> int {
return f1(f2(n));
};
}
function<int(int)> print(const string& msg) {
return [msg](int n) -> int {
cout << "print: " << msg << endl;
return n;
};
}
function<int(int)> inc = [](int n) -> int {
cout << "in inc lambda: " << n << endl;
return n+1;
};
//calls the given function `f` only when `n` is less then `m`
function<int(int)> guarded(int m, function<int(int)> f) {
auto g = [m,f](int n) -> int { return n<m? f(n) : m; };
return compose(g, print("guarded"));
}
/* start of the program */
function<int(int)> recursion();
function<int(int)> go =
compose(guarded(10, recursion()), compose(inc, print("go")));
function<int(int)> recursion() {
return compose(go, print("recursion"));
}
int main() {
try {
recursion()(0);
} catch (bad_function_call e) {
cout << "bad_function_call: " << e.what() << endl;
}
return 0;
}
答案 0 :(得分:6)
在原始代码中,recursion()
初始化期间会调用go
。 recursion
本身会尝试使用go
的值,但此时go
尚未初始化,从而导致问题。
在替代代码中,go
的初始化仅在不调用go
的情况下将lambda分配给recursion
。稍后调用recursion
时,go
已经初始化。