我寫以下代碼:C++:添加自動分配對象到一個std ::矢量
#include <iostream>
#include <vector>
using namespace std;
class AClass
{
public:
int data;
AClass()
{ data = -333; cout << "+ Creating default " << data << endl; }
AClass(const AClass ©)
{ data = copy.data; cout << "+ Creating copy of " << data << endl; }
AClass(int d)
{ data = d; cout << "+ Creating " << data << endl; }
~AClass()
{ cout << "- Deleting " << data << endl; }
AClass& operator = (const AClass &a)
{ data = a.data; cout << "= Calling operator=" << endl; }
};
int main(void)
{
vector<AClass> v;
for (int i = 3; i--;)
v.push_back(AClass(i));
vector<AClass>::iterator it = v.begin();
while (it != v.end())
cout << it->data << endl, it++;
return 0;
}
並從該程序的輸出結果是:
+ Creating 2
+ Creating copy of 2
- Deleting 2
+ Creating 1
+ Creating copy of 1
+ Creating copy of 2
- Deleting 2
- Deleting 1
+ Creating 0
+ Creating copy of 0
+ Creating copy of 2
+ Creating copy of 1
- Deleting 2
- Deleting 1
- Deleting 0
2
1
0
- Deleting 2
- Deleting 1
- Deleting 0
然後,我改變的類:
class AClass
{
public:
int data;
AClass(int d)
{ data = d; cout << "+ Creating " << data << endl; }
~AClass()
{ cout << "- Deleting " << data << endl; }
};
,輸出變爲:
+ Creating 2
- Deleting 2
+ Creating 1
- Deleting 2
- Deleting 1
+ Creating 0
- Deleting 2
- Deleting 1
- Deleting 0
2
1
0
- Deleting 2
- Deleting 1
- Deleting 0
看起來,矢量在添加新的對象時正在製作現有對象的副本,但似乎有很多不必要的分配/刪除正在發生。爲什麼是這樣?另外,爲什麼第二個版本在我沒有提供拷貝構造函數時工作?
謝謝!這有很大的幫助 - 你的回答解決了問題的每一部分。 – milesleft 2011-05-31 22:43:20