我想要下面的代碼創建5個類「test」的對象,每次創建時調用構造函數,將它們存儲在一個向量中,打印「lalalala」一次,然後運行析構函數並銷燬創建的對象。我希望析構函數爲我創建的每個對象運行一次,但不要超過一次。C++中的構造函數和析構函數與C#比較
我認爲在下面的例子中,C++創建了多個不需要的對象的副本,否則它會調用析構函數多次。我不確定。試過海灣合作委員會和鏗鏘沒有區別。嘗試堆棧和堆分配,以及std :: move。所有產生相同的結果,方式更多的析構函數調用比我所要求的。
另外我注意到一些但不是所有的C++析構函數在我打印「lalala」之前調用。
爲什麼這個C++代碼運行析構函數的17倍:
#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;
}
雖然此C#代碼不正是我想要的東西,5構造函數和析構函數5。
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");
}
}
您還需要計數複製構造函數。 – SergeyA
http://stackoverflow.com/a/2625089/1060270說明可能有幫助 – amit