emplace_back

c++11 的 list deque 和 vector 增加了emplace_back函数,相对于push_back函数,它减少了一次类的构造,因此效率更高,推荐使用。

#include <list>
#include <string>
#include <iostream>
 
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(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) = default;
};
 
int main()
{
    std::list<President> elections;
    std::cout << "emplace_back:\n";
    elections.emplace_back("Nelson Mandela", "South Africa", 1994);
 
    std::list<President> reElections;
    std::cout << "\npush_back:\n";
    reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));

}

输出:

emplace_back:
I am being constructed.
 
push_back:
I am being constructed.
I am being moved.

我们看到,emplace_back通过使用“可变长模板”减少了一次构造函数的执行。

和 push_back 一样,emplace_back 可能会导致 vector, deque 迭代器失效,具体就是:

1. 如果vector size() 大于 capacity() ,empace_back之后,所有的迭代器和引用失效; 否则,仅仅 end() 失效

2. deque 所有迭代器失效,没有引用失效

posted @ 2018-12-29 11:04  二狗啸地  阅读(3322)  评论(0编辑  收藏  举报