1. 主要区别
如果要将一个临时变量push到容器的末尾:
- push_back()需要先构造临时对象,再将这个对象拷贝到容器的末尾,
- emplace_back()则直接在容器的末尾构造对象,这样就省去了拷贝的过程。
2. 自定义一个数据类型测试
2.1 push_back
class A
{
public:
A(int i) {
this->str = std::to_string(i);
cout << "构造函数" << endl;
};
~A() {};
A(const A& other) :str(other.str) {
cout << "拷贝构造函数" << endl;
};
string str;
};
void fun() {
vector<A> v1;
v1.reserve(3);
for (int i = 0; i < 3; i++)
{
v1.push_back(A(i));
//v1.emplace_back(i);
}
}
输出是3次构造, 3次拷贝:
2.2 emplace_back
传入的参数是什么很重要!!!!!!
如果传入A(i),也是3次构造,3次拷贝。因为A(i)相当于构造了对象,再把对象传入。
void fun() {
vector<A> v1;
v1.reserve(3);
for (int i = 0; i < 3; i++)
{
v1.emplace_back(A(i)); // 传入 A(i)
//v1.emplace_back(i);
}
}
直接传入i,emplace back 会自动在末尾构造对象,不需要拷贝。
void fun() {
vector<A> v1;
v1.reserve(3);
for (int i = 0; i < 3; i++)
{
//v1.emplace_back(A(i)); // 传入 A(i)
v1.emplace_back(i); //直接传i
}
}
从输出结果可以看到,仅仅调用了三次构造函数!!!