Which, if any, C++ compilers do tail-recursion optimization?

前端 未结 5 737
再見小時候
再見小時候 2020-11-22 12:45

It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates th

5条回答
  •  无人及你
    2020-11-22 13:43

    As well as the obvious (compilers don't do this sort of optimization unless you ask for it), there is a complexity about tail-call optimization in C++: destructors.

    Given something like:

       int fn(int j, int i)
       {
          if (i <= 0) return j;
          Funky cls(j,i);
          return fn(j, i-1);
       }
    

    The compiler can't (in general) tail-call optimize this because it needs to call the destructor of cls after the recursive call returns.

    Sometimes the compiler can see that the destructor has no externally visible side effects (so it can be done early), but often it can't.

    A particularly common form of this is where Funky is actually a std::vector or similar.

提交回复
热议问题