C++11中 emplace_back与push_back的区别

使用empalce操作

新标准中加入了三个新成员——emplace、emplace_front、emplace_back。这些是操作构造,而不是拷贝构造。
这些操作分别对应以前的insert、push_front、push_back。允许我们将元素放置在一个指定位置之前容器头部容器尾部。

当调用push或insert成员函数时,我们将元素类型的对象传递给它们,这些对象被拷贝到容器中。而当我们调用一个emplace成员函数时,则是将参数传递给元素类型的构造函数。emplace成员使用这些参数在容器管理的内存空间中直接构造元素。
我们看一个例子:
来源:原文链接

#include   
#include   
#include   

struct President  
{  
    std::string name;  
    std::string country;  
    int year;  

    President(std::string p_name, std::string p_country, int p_year)  
        : name(std::move(p_name)), country(std::move(p_country)), year(p_year)  
    {  
        std::cout << "I am being constructed.\n";  
    }
    President(const President& other)
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
    {
        std::cout << "I am being copy constructed.\n";
    }
    President(President&& other)  
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)  
    {  
        std::cout << "I am being moved.\n";  
    }  
    President& operator=(const President& other);  
};  

int main()  
{  
    std::vector<President> elections;  
    std::cout << "emplace_back:\n";  
    elections.emplace_back("Nelson Mandela", "South Africa", 1994); //没有类的创建  

    std::vector<President> reElections;  
    std::cout << "\npush_back:\n";  
    reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));  

    std::cout << "\nContents:\n";  
    for (President const& president: elections) {  
       std::cout << president.name << " was elected president of "  
            << president.country << " in " << president.year << ".\n";  
    }  
    for (President const& president: reElections) {  
        std::cout << president.name << " was re-elected president of "  
            << president.country << " in " << president.year << ".\n";  
    }

}

输出:
C++11中 emplace_back与push_back的区别_第1张图片
push_back会创建一个临时对象,并将其压入容器中。而emplace_back时会在容器管理的内存中直接创建对象。
emplace函数直接在容器中构造元素。所以传递给emplace函数的参数必须与构造函数参数类型相匹配。

你可能感兴趣的:(C/C++)