#include <iostream>
#include <vector>
class Data{
public:
Data(int i):v(i){
std::cout<<"ctor"<<std::endl;
}
Data(const Data &d){
v=d.v;
std::cout<<"copy"<<d.v<<std::endl;
}
Data(Data &&d) {
v=d.v;
std::cout << "move"<<d.v<< std::endl;
}
operator =(const Data &d){
std::cout<<"copy assign "<<d.v<<std::endl;
}
~Data(){
//std::cout<<"dtor"<<std::endl;
}
int get(){return v;}
private:
int v=-1;
};
int test_fun(){
std::vector<Data> vec;
//vec.reserve(4);
std::cout<<"cap:"<<vec.capacity()<<std::endl;
vec.push_back(Data(1));
std::cout<<"cap:"<<vec.capacity()<<std::endl;
vec.push_back(Data(2));
std::cout<<"cap:"<<vec.capacity()<<std::endl;
vec.push_back(Data(3));
std::cout<<"cap:"<<vec.capacity()<<std::endl;
std::cout<<vec.size()<<std::endl;
for(auto ele:vec){
std::cout<<ele.get()<<std::endl;
}
}
int main(){
//Data d1,d2;
test_fun();
return 0;
}
本文代码主要测试vector在插入元素时,一共调用了多少次元素的拷贝构造函数。在vector空间发生扩容时,vector会调用元素的拷贝构造函数。
Reference:
[1]c++中vector的拷贝构造过程