push_bach():
首先调用构造函数构造一个临时对象,然后在容器尾部区域利用这个临时对象进行拷贝构造,最后释放临时变量。
emplace_back():
这个元素原地构造,不需要触发拷贝构造和转移构造。
详细测试见代码:
#include<iostream>
#include <vector>
using namespace std;
class test
{
public:
int id;
test() :id(0)
{
cout << "默认构造" << endl;
};
test(int n) :id(n)
{
cout << "带参构造" << endl;
};
test(const test& rhs)
{
this->id = rhs.id;
cout << "拷贝构造" << endl;
}
test(const test&& rhs) noexcept
{
this->id = rhs.id;
cout << "移动拷贝构造" << endl;
}
test& operator=(const test& rhs)
{
this->id = rhs.id;
cout << "赋值构造" << endl;
}
test&& operator=(const test&& rhs) noexcept
{
this->id = rhs.id;
cout << "移动赋值构造" << endl;
}
};
int main()
{
test test1(1);
test test2(2);
vector<test> v;
v.reserve(20); //提前准备好空间
cout << "push_back(test1)" << endl; //都是拷贝构造
v.push_back(test1);
cout << "push_back(test2)" << endl;
v.emplace_back(test2);
cout << endl;
cout << "push_back(1)" << endl;
v.push_back(1); //push_back先用参数1生成临时对象,然后在进行移动拷贝构造
cout << "push_back(2)" << endl;
v.emplace_back(2); //emplace_back直接利用参数1进行带参构造
cout << endl;
cout << "push_back(move(test1))" << endl; //移动赋值两者都一样
v.push_back(move(test1));
cout << "emplace_back(move(test2))" << endl;
v.emplace_back(move(test2));
cout << endl;
}
测试结果: