push_back和emplace_back区别:
emplace_back() 和 push_back() 功能上类似,但底层实现机制是不同的。push_back() 向容器尾部添加元素时,首先会创建这个元素(调用构造函数或者拷贝构造函数),然后再将这个元素拷贝或者移动到容器中(调用复制构造函数或者移动构造函数);而 emplace_back() 在实现时,则是直接在容器尾部创建这个元素,也就是只会调用一次构造函数。
例子:
#include <vector>
#include <iostream>
using namespace std;
class testDemo
{
public:
testDemo(int num):num(num){
std::cout << "call constructor function" << endl;
}
testDemo(const testDemo& other) :num(other.num) {
std::cout << "call copy constructor function" << endl;
}
testDemo(testDemo&& other) :num(other.num) {
std::cout << "call move constructor function" << endl;
}
private:
int num;
};
int main()
{
cout << "emplace_back:" << endl;
std::vector<testDemo> demo1;
demo1.emplace_back(2);
cout << "push_back:" << endl;
std::vector<testDemo> demo2;
demo2.push_back(2);
}
结果如下:
emplace_back:
call constructor function
push_back:
call constructor function
call move constructor function
#include <vector>
#include <iostream>
using namespace std;
class testDemo
{
public:
testDemo(int num):num(num){
std::cout << "call constructor function" << endl;
}
testDemo(const testDemo& other) :num(other.num) ,num1(1111){
std::cout << "call copy constructor function" << endl;
}
testDemo(testDemo&& other) :num(other.num) {
std::cout << "call move constructor function" << endl;
}
~testDemo(){std::cout << "~~~~~~~~~" << std::endl;}
int num1;
private:
int num;
};
int main()
{
testDemo demo1(10);
std::vector<testDemo> vec;
demo1.num1 = 100;
vec.emplace_back(demo1);
std::cout << vec[0].num1 << std::endl;
}
结果:
num1的值并未传入,仍然为0
./a.out
call constructor function
call copy constructor function
0