C++ push_back和emplace_back的区别

基本类型情况西,两者几乎没什么区别
但是再自定义类型的时候?emplace——back更高效,但是emplace_back 没有类型检查的安全;只有运行时候才会报错。

#include <vector> 
#include <iostream> 
using namespace std;
class testDemo
{
public:
    explicit 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;
    }
    int getnum()
    {
        return num;
    }
private:
    int num;
};

int main()
{
    cout << "emplace_back:" << endl;
    std::vector<testDemo> demo1;
    demo1.emplace_back(2);
    cout << demo1[0].getnum() << std::endl;
    cout << "push_back:" << endl;
    std::vector<testDemo> demo2;
    testDemo test(2);
    demo2.push_back(test);
}

#-----------------------------------------------------------------------------------------------------------------

#include <vector> 
#include <iostream> 
using namespace std;
class testDemo
{
public:
    explicit 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;
    }
    int getnum()
    {
        return num;
    }
private:
    int num;
};

int main()
{
    cout << "emplace_back:" << endl;
    std::vector<testDemo> demo1;
    demo1.emplace_back("asdasd");
    cout << demo1[0].getnum() << std::endl;
    cout << "push_back:" << endl;
    std::vector<testDemo> demo2;
    testDemo test(2);
    demo2.push_back(test);
}

报错
在这里插入图片描述
为什么会高效?

emplace_back:
call constructor function
11
push_back:
call constructor function
call copy constructor function

原理是? 直接再最后构造对象 ,然后push_back 先构造 ,再转移。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值