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.
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.
Also i noticed some but not all C++ destructors are called before i print "lalala".
Why does this C++ code runs the destructor 17 times :
#include <iostream>
#include <vector>
using namespace std;
class test
{
public:
int t;
test(int i)
{
t = i;
cout << "Created instance " << t << ". \n";
}
~test()
{
cout << "(*)Deleted instance " << t << ".\n";
}
};
int main()
{
vector <test> V;
for(int i = 1; i <= 5; i++)
{
test D(i);
V.push_back(D);
}
cout << "LALALLALA \n";
return 0;
}
While this C# code does exactly what i want, 5 constructors and 5 destructors.
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<test> lst = new List<test>();
for(int i = 0; i < 5; i++)
{
test temp = new test(i);
lst.Add(temp);
}
Console.WriteLine("LALALLALA \n");
}
}