Visual C ++尾部调用优化 [英] Visual C++ Tail Call Optimization
问题描述
根据该问题的答案:
哪个,如果有的话,C ++编译器做尾递归优化?
似乎,编译器应该做尾递归优化。
According to answers to that question: Which, if any, C++ compilers do tail-recursion optimization? it seems, that compiler should do tail-recursion optimization.
但我已经尝试过的选项,似乎编译器不能做模板函数的优化。
But I've tried proposed options and it seems that compiler can't do this optimization in case of template functions. Could it be fixed somehow?
推荐答案
我不使用MS编译器,但GCC当然可以做尾递归优化模板。给定此函数:
I don't use the MS compilers, but GCC can certainly do tail-recursion optimisation for templates. Given this function:
template <typename T>
T f( T t ) {
cout << t << endl;
if ( t == 0 ) {
return t;
}
return f( t - 1 );
}
生成的代码是:
5 T f( T t ) {
6 cout << t << endl;
- 0x401362 <main+22>: mov %esi,0x4(%esp)
- 0x401366 <main+26>: movl $0x4740c0,(%esp)
- 0x40136d <main+33>: call 0x448620 <_ZNSolsEi>
- 0x401372 <main+38>: mov %eax,%ebx
7 if ( t == 0 ) {
- 0x4013a5 <main+89>: test %esi,%esi
- 0x4013a7 <main+91>: je 0x4013c8 <main+124>
8 return t;
9 }
10 return f( t - 1 );
- 0x4013a9 <main+93>: dec %esi
- 0x4013aa <main+94>: jmp 0x401362 <main+22>
11 }
你可以看到递归调用已经变成了跳转函数的开始。如果代码是在启用了优化(这种情况下为-O2)的情况下编译的,那么此优化仅由GCC执行 - 也许对于MS C ++也是如此?
You can see that the recursive call has been turned into a jump back to the start of the function. This optimisation is only performed by GCC if the code is compiled with optimisations enabled (-O2 in this case) - perhaps the same is true for MS C++?
这篇关于Visual C ++尾部调用优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!