class B
{
private:
int _x;
public:
int get(){return _x;};
B(int x=10):_x(x){cout<<"Default constructor "<<endl;}
~B(){cout<<"destructor "<<endl;}
B(const B &rhs){cout<<"copy constructor"<<endl;}
B& operator =(const B &rhs){cout<<"copy assignment operator"<<endl;}
int operator *(){cout<<"operator *"<<endl;return _x;}
};
int main()
{
vector<B> v;
int i;
vector<B>::iterator ii=v.begin();
for(i=0;i<1;i++)
{
v.push_back(*(new B(i*100)));
}
ii = v.begin();
cout<<"#####################"<<endl;
ii = v.insert(ii+1,*(new B()));
cout<<"#####################"<<endl;
return 0;
}
Default constructor
copy constructor
#####################
Default constructor
1. copy constructor
2. copy constructor
destructor
#####################
destructor
destructor
這是爲什麼在v.insert(II,*(新B()));, 2個拷貝構造函數的調用??
C++是**不是** Java。你應該**從不**寫入任何東西:'push_back(*(new B(i * 100)))''。它在堆上創建一個B *實例,然後忘掉它。做事情你基本上是在泄漏記憶。你可以使用'push_back(B(i * 100))'或者''push_back(i * 100)''因爲你的'B'類可以隱式構造。 – ereOn 2012-02-28 15:30:16