title: Constructors and Destructors in C++ compared to C#
body: <p>I want the following code to create 5 objects of the class "test" which call the constructor each time one is created,store them in a vector, print "lalalala" once, and then run the destructors and destroy the created objects. I want the destructor to run once for each object i created not more than once.</p>
  
  <p>I think C++ in the following example is creating multiple extra copies of objects i do not want or else it calls the destructor way more times that it should. I am not sure. Tried gcc and clang no difference. Tried both with stack and heap allocation, as well as std::move. All produce the same results, way more destructor calls than i asked for.</p>
  
  <p>Also i noticed some but not all C++ destructors are called before i print "lalala".</p>
  
  <p>Why does this C++ code runs the destructor 17 times :</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  using namespace std;
  
  
  class test
  {
  public:
      int t;
      test(int i)
      {
          t = i;
          cout &lt;&lt; "Created instance " &lt;&lt; t &lt;&lt; ". \n";
      }
      ~test()
      {
          cout &lt;&lt; "(*)Deleted instance " &lt;&lt;  t &lt;&lt;  ".\n";
      }
  };
  
  int main()
  {
      vector &lt;test&gt; V;
  
      for(int i = 1; i &lt;= 5; i++)
      {
          test D(i);
          V.push_back(D);
      }
     cout &lt;&lt; "LALALLALA \n";
     return 0;
  }
  </code></pre>
  
  <p>While this C# code does exactly what i want, 5 constructors and 5 destructors.</p>
  
  <pre><code>using System.IO;
  using System;
  using System.Collections.Generic;
  class Program
  {
      class test
      {
          public int t;
          public test(int i)
          {
              t = i;
              Console.Write ("Created instance ");
              Console.Write (t.ToString());
              Console.WriteLine(".");
          }
  
          ~test()
          {
              Console.Write( "(*)Deleted instance ");
              Console.Write(t.ToString());
              Console.WriteLine(".");
          }
  
      }
      static void Main()
      {
          List&lt;test&gt; lst = new List&lt;test&gt;();
          for(int i = 0; i &lt; 5; i++)
          {
              test temp = new test(i);
              lst.Add(temp);
          }
          Console.WriteLine("LALALLALA \n");   
      }
  }
  </code></pre>