emplace_back()

 
templateclass... Args >
void emplace_back( Args&&... args );
  (C++11 起)
(C++17 前)
templateclass... Args >
reference emplace_back( Args&&... args );
  (C++17 起)
(C++20 前)
templateclass... Args >
constexpr reference emplace_back( Args&&... args );
  (C++20 起)
     

添加新元素到容器尾。元素通过 std::allocator_traits::construct 构造,通常用放置式 new 于容器所提供的位置原位构造元素。实参 args... 以 std::forward<Args>(args)... 转发到构造函数。

如果操作后新的 size() 大于原 capacity() 则会发生重分配,这种情况下,指代元素的所有迭代器(包括 end() 迭代器)和所有引用均会失效。否则仅有 end() 迭代器失效。

 

 

下列代码用 emplace_back 追加 President 类型的对象到 std::vector。它演示 emplace_back 如何转发参数给 President 的构造函数,并展示如何用 emplace_back 避免用 push_back 时的额外复制或移动操作。

#include <vector>
#include <cassert>
#include <iostream>
#include <string>
 
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 << "我正被构造。\n";
    }
    President(President&& other)
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
    {
        std::cout << "我正被移动。\n";
    }
    President& operator=(const President& other) = default;
};
 
int main()
{
    std::vector<President> elections;
    std::cout << "emplace_back:\n";
    auto& ref = elections.emplace_back("Nelson Mandela", "South Africa", 1994);
    assert(ref.year == 1994 && "使用到所创建对象的引用 (C++17)");
 
    std::vector<President> reElections;
    std::cout << "\npush_back:\n";
    reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));
 
    std::cout << "\n内容:\n";
    for (President const& president: elections) {
        std::cout << president.name << ""
                  << president.country << " " << president.year << " 年的当选总统。\n";
    }
    for (President const& president: reElections) {
        std::cout << president.name << ""
                  << president.country << " " << president.year << " 年的连任总统。\n";
    }
}
emplace_back:
我正被构造。
 
push_back:
我正被构造。
我正被移动。
 
内容:
Nelson Mandela 是 South Africa 1994 年的当选总统。
Franklin Delano Roosevelt 是 the USA 1936 年的连任总统。

 

posted @ 2024-03-06 13:24  He_LiangLiang  阅读(7)  评论(0编辑  收藏  举报