C++中push_back和emplace_back的区别

没找到讲明白了的博客,但是测试代码写了一下。

结论是:push_back你传new出来的对象就好,emplace_back你传构造函数所需要的参数,让他自己构造比较好。

#include<iostream>
#include<cstring>
#include<cmath>
#include <vector>
#include <Windows.h>
using namespace std;

class A
{
public:
    int n;
    A(int n)
    {
        this->n=n;
        cout<<"construct"<<endl;
    }
    A(const A &a)
    {
        this->n=a.n;
        cout<<"copy construct"<<endl;
    }
    A(A &&a)
    {
        this->n=a.n;
        cout<<"move construct"<<endl;
    }
    ~A()
    {
        cout<<"deconstruct"<<endl;
    }

};

int main()
{
    vector<A> v;
    cout<<"v.push_back(A(1));"<<endl;
    v.push_back(A(1));
    cout<<endl;

    cout<<"v.emplace_back(A(2));"<<endl;
    v.emplace_back(A(2));
    cout<<endl;

    cout<<"v.push_back(move(A(3)));"<<endl;
    v.push_back(move(A(3)));
    cout<<endl;

    cout<<"v.emplace_back(move(A(4)));"<<endl;
    v.emplace_back(move(A(4)));
    cout<<endl;

    cout<<"v.push_back(5);"<<endl;
    v.push_back(5);
    cout<<endl;

    cout<<"v.emplace_back(6);"<<endl;
    v.emplace_back(6);
    cout<<endl;

    for(int i=0;i!=v.size();i++)
    {
        cout<<v[i].n<<endl;
    }

    return 0;
}

v.push_back(A(1));
construct
move construct
deconstruct

v.emplace_back(A(2));
construct
move construct
copy construct
deconstruct
deconstruct

v.push_back(move(A(3)));
construct
move construct
copy construct
copy construct
deconstruct
deconstruct
deconstruct

v.emplace_back(move(A(4)));
construct
move construct
deconstruct

v.push_back(5);
construct
move construct
copy construct
copy construct
copy construct
copy construct
deconstruct
deconstruct
deconstruct
deconstruct
deconstruct

v.emplace_back(6);
construct

1
2
3
4
5
6
deconstruct
deconstruct
deconstruct
deconstruct
deconstruct
deconstruct
文章目录