看c++ primer第4版,第9章,
9.12 容器内元素的类型约束
书中提到2点:
1元素类型必须支持赋值运算
2元素类型的对象必须可以复制
写了一个简单的类Data,测试vector在初始化的时候,Data是怎么进行初始化或者赋值的.Data类里自定义了默认构造函数,拷贝构造函数,重载了=运算符.
#include <iostream>
#include <vector>
#include <list>
#include <string>
using namespace std;
class Data{
public:
Data(int i){
this->i = i;
cout << step++ << ":Data one parameter construct is called" <<endl;
}
Data(){
i = -1;
cout << step++ <<":the default construct is called" << endl;
}
Data operator=(const Data& d){
this->i = d.i;
cout << step++ << ":operator = is called right value = "<< d.i << endl;
return *this;
}
Data(const Data& d){
this->i = d.i;
cout << step++ << ":copy construct is called right value = " << d.i<<endl;
}
private:
static int step; //记录输出的步骤
int i;
};
int Data::step =1;
int
main()
{
Data d(5);
vector<Data> vecData(3, 10);//调用vector 两个参数的构造函数,3是vector长
// 度,10 初始化Data的值
}
运行结果:
1:Data one parameter construct is called
2:the default construct is called
3:copy construct is called right value = 10
4:copy construct is called right value = 10
5:copy construct is called right value = 10
说明: 1 在执行vector<Data> vecData(3,10)的时候,调用了一次Data(int i) 构造函数,3次的拷贝构造函数,生成3个Data对象.如果不指定初始化对象的初始值,Data就会调用默认构造函数,例如把vector<Data> vecData(3,10);改为
vector<Data> vecData(3);
vector在调用push_back操作的时候都做了什么?.把main函数修改为:
int
main()
{
Data d(5);
Data dd(10);
vector<Data> vecData; //定义一个长度为1的vector<Data>
vecData.push_back(d); //插入一个元素;
vectorData.push_back(dd);
}
运行的结果:
1:Data one parameter construct is called
2:Data one parameter construct is called
3:copy construct is called right value = 5
4:copy construct is called right value = 5
5:copy construct is called right value = 10
说明:在插入第二个元素的时候, vectorData.push_back(dd)输出了4和5,为什么Data多做了一次value=5的copy construct?
结合上面的例子.
容器元素约束类型,第2点,我觉的作者的本意是说,元素的对象必须有正确的复制拷贝函数.上面的测试中,容器在初始化或者插入元素的时候,容器生成元素的副本.只用到了构造函数.那什么时候会用到赋值运算呢?