对以下程序及其输出感到有点困惑。
请有人澄清一下吗?
#include <iostream>
#include <vector>
using namespace std;
class sample
{
public:
int a;
sample( ){ cout<<" Am in Default Cons "<< a << "\n"; }
sample( int b ){ a=b; cout<<" Am in Cons "<< a << "\n"; }
sample(const sample& s){ a=s.a; cout<<" Am in copy " <<s.a<<"\n"; }
~sample(){ cout<<" Am in Des "<<a <<"\n"; }
};
int main()
{
vector < sample > Object;
{
Object.push_back( sample( 1 ));
Object.push_back( sample( 2 ));
cout<<" End of loop \n";
}
cout<<" \n End of Program \n";
return 0;
}
,输出
Am in Cons 1 // Understood this is for object 1 creation Am in copy 1 // Understood this is for object 1 copy to vector Am in Des 1 // Understood this is for object 1 destruction. Am in Cons 2 // Understood this is for object 2 creation Am in copy 2 // Understood this is for object 2 copy to vector Am in copy 1 // **Don't understand this COPY CALL** Am in Des 1 // **Don't understand this DESTRUCTOR CALL** Am in Des 2 // Understood this is for object 2 destruction. End of loop End of Program Am in Des 1 //// Understood this is for object 1 destruction in vector . Am in Des 2 //// Understood this is for object 2 destruction in vector .
答案 0 :(得分:8)
std::vector
是一个动态数组。添加元素并且其内部缓冲区的容量已满时,vector
需要:
(不一定按此顺序。)
步骤2.涉及您不理解的复制构造函数。第3步涉及你不理解的析构函数。
要防止此(低效)行为,请在插入元素之前使用std::vector::reserve
(如果可以)。然后不会重新分配,也不会发生隐藏的复制/移动元素。