title: C++ how to declare a "complex" object inside a loop?
body: <p><em>edit: As mentioned by @HolyBlackCat
  &quot;If you need it to retain it's [a variable's] value between iterations, it has to stay outside.&quot; This is of course true of even primitive types, eg. int. So this question is actually just noise, sorry.</em></p>
  <p>I'm trying to get my head around how to be consistent when declaring objects, the &quot;declare variable inside or outside loop?&quot; issue for variables that are only used inside a loop. See eg. <a href="https://stackoverflow.com/questions/7959573/declaring-variables-inside-loops-good-practice-or-bad-practice">Declaring variables inside loops, good practice or bad practice?</a>.</p>
  <p>Consider the below examples. Let V be an object which has a default constructor.</p>
  <pre><code>                                  // Example 1
  std::vector&lt;int&gt; V;               // Works as intended
  for (int i=0; i&lt;2; i++) {         // ...but V should be declared inside loop(?)
      V.push_back(i);
      // V used only inside loop
  }                                 
                                    // Example 2 
  for (int i=0; i&lt;2; i++) {         // OK Syntax, Wrong Semantics
      std::vector&lt;int&gt; V;           // V is &quot;created&quot; anew in each loop-step
      V.push_back(i);
      // V used only inside loop         
  }
                                    // Example 3
  for (int i=0; i&lt;2; i++) {         // Syntax Error, other syntax possible?
      std::vector&lt;int&gt; V.push_back(i);
      // V used only inside loop 
  }
  </code></pre>
  <p>Example 1: Defines the approximate semantics im looking for - besides that V is local to the loop and I would prefer to define V inside the loop.</p>
  <p>Example 2: Defines V inside the loop but also creates it anew in each loop-step, this is NOT the desired semantics.</p>
  <p>Example 3: &quot;Nice try&quot; exploration of syntax - Im trying to declare and &quot;immediately use&quot; the object V. This is illegal syntax.</p>
  <p>If, at the end of the day, many types of objects are most elegantly declared outside the loop (as it would seem to be the case with V in the example; otherwise, if declared inside the loop, the declaration would have to be somehow &quot;guarded&quot;) then i might just lean to declaring everything outside the loop, just before the loop, instead of inside the loop...</p>
  <p>Please give me advice on this issue, how to get the semantics of Example 1 but with V declared inside the loop (if possible).</p>