尾递归没有发生 [英] Tail-recursion not happening
问题描述
我在C ++项目中使用 g ++(Ubuntu 4.8.2-19ubuntu1)4.8.2
。我写了一个这样的函数:
I'm using g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
in a C++ project. I wrote a function that kind of does this:
template<typename T, T (*funct)(int) >
multiset<T> Foo(const multiset<T>& bar, int iterations) {
if (iterations == 0) return bar;
multiset<T> copy_bar(bar);
T baz = funct(copy_bar.size());
if (baz.attr > 0)
return Foo<T,funct>(copy_bar, 100);
else
return Foo<T,funct>(bar, iterations - 1);
}
我得到 bad_alloc()exception
,所以我用 gdb
测试了函数,结果发现没有尾递归发生,这是我期待的,因为<$ c $之后没有语句c> return s。
I was getting bad_alloc() exception
so I tested the function with gdb
and turns out that there's no tail-recursion happening, which I was expecting since there are no statements after the return
s.
注意:我尝试使用-O2编译标志,但它不起作用
NOTE: I tried with -O2 compilation flag but it didn't work
推荐答案
你的函数是不是尾递归,因为递归调用之后仍有工作要做:销毁 copy_bar
(它有一个非平凡的析构函数),也可能是 baz
(如果类型 T
也有一个非平凡的析构函数)。
Your function is not tail-recursive, since there's still work to do after the recursive call: Destruction of copy_bar
(which has a non-trivial destructor) and possibly also of baz
(if the type T
also has a non-trivial destructor).
这篇关于尾递归没有发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!