vector emplace_back和push_back的原理和区别

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值