push_back 加入元素需要先构造然后拷贝或移动,而emplace_back可以原地构造对象,然后加入到容器中,可以减少一次拷贝或构造。

测试代码如下:

typedef struct testEmplace 
{
    testEmplace()
    {
        std::cout << "create testEmplace" << std::endl;
    }

    testEmplace(int a)
    {
        std::cout << "create testEmplace with param" << std::endl;
    }

    testEmplace(const testEmplace& src)
    {
        std::cout << "copy testEmplace" << std::endl;
    }

    testEmplace(testEmplace&& src)
    {
        std::cout << "move testEmplace" << std::endl;
    }
    
    ~testEmplace()
    {
        std::cout << "destroy testEmplace" << std::endl;
    }

    testEmplace& operator = (const testEmplace& rht)
    {
        std::cout << " operator =() testEmplace" << std::endl;
    }
}testEmplace;

int main(int argc, char* argv[])
{
    std::vector<testEmplace> test;
    test.reserve(10); //指定初始容量,防止后续加入元素操作引发容器自动增长

    testEmplace a;//构造
    test.push_back(a);//拷贝构造
    std::cout << "==============" << std::endl;

    testEmplace b;//构造
    test.push_back(std::move(b));//移动构造
    std::cout << "==============" << std::endl;

    test.emplace_back(1);//原地构造
    std::cout << "==============" << std::endl;

    testEmplace c;//构造
    test.emplace_back(c);//拷贝构造
    std::cout << "==============" << std::endl;

    testEmplace d;//构造
    test.emplace_back(std::move(d));//移动构造
 
    std::cin.get();

    return 0;
}

输出如下:

create testEmplace
copy testEmplace
==============
create testEmplace
move testEmplace
==============
create testEmplace with param
==============
create testEmplace
copy testEmplace
==============
create testEmplace
move testEmplace
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐