title: Tail-recursion with objects
body: <p>I have a recursive function that I would like to make tail-recursive. My actual problem is more complex and context-dependent. But the issue I would like to solve is demonstrated with this simple program:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  struct obj
  {
      int n;
  
      operator int&amp;() { return n; }
  };
  
  int tail(obj n)
  {
      return tail(obj{ n + 1 &gt; 1000 ? n - 1000 : n + 1 });
  }
  
  int main()
  {
      tail(obj{ 1 });
  }
  </code></pre>
  
  <p>It seems natural that this is tail-recursive. It is not, though, because the destructor of <code>obj n</code> has to be called each time. At least MSVC13 (edit:) <em>and MSVC15</em> do not optimize this. If I replace <code>obj</code> with int and change the calls accordingly, it becomes tail-recursive as expected.</p>
  
  <p>My actual question is: Is there an easy way to make this tail-recursive apart from just replacing <code>obj</code> with <code>int</code>? I am aiming for performance benefits, so playing around with heap-allocated memory and <code>new</code> is most likely not helpful.</p>