title: C++ loop stack allocation
body: <p>While doing an assignment for a course and learning C++ while doing it, I was reading up on when to use stack allocation and dynamic allocation. I'm aware that in a lot of cases it is easier and better to use stack allocation. But there is a simple situation I'm puzzeled about.</p>
  
  <p>Lets say you have a for loop:</p>
  
  <pre><code>for(int i = 0; i &lt; 10; i++)
  {
     MyObject obj(file);
     obj.doSomething();
  }
  </code></pre>
  
  <p>Now the problem is that if the Object contains state, it keeps it state (stays the same object) while iterating through the iterations from 1 til 10. Maybe coming from a Java/C# background gets me on the wrong path. But I only see two ways of solving this:</p>
  
  <ol>
  <li>Using dynamic memory.</li>
  <li>Not giving file to the constructor but instead to the method <code>doSomething(file)</code> but this isn't very nice if you have more than one method manipulating the file object e.g. <code>doSomethingElse(file)</code>.</li>
  </ol>
  
  <p>So what do you guys do in such a situation, or do you never get yourself in such a situation at all? </p>
  
  <p><strong>Update:</strong>
  Turns out i misunderstood and it is working as expected. Check the awnsers below! Thanks everyone</p>