std::list<T,Allocator>::emplace_back
来自 cppreference.com
template< class... Args > void emplace_back( Args&&... args ); |
(自 C++11 起) (直到 C++17) |
|
template< class... Args > reference emplace_back( Args&&... args ); |
(自 C++17 起) | |
将一个新元素附加到容器的末尾。该元素是通过 std::allocator_traits::construct 构造的,该函数通常使用就地 new 在容器提供的地址上构造元素。参数 args... 作为 std::forward<Args>(args)... 传递给构造函数。
没有迭代器或引用被失效。
内容 |
[编辑] 参数
args | - | 要转发给元素构造函数的参数 |
类型要求 | ||
-T(容器的元素类型) 必须满足 EmplaceConstructible 的要求。 |
[编辑] 返回值
(无) |
(直到 C++17) |
对插入元素的引用。 |
(自 C++17 起) |
[编辑] 复杂度
常数。
[编辑] 异常
如果由于任何原因抛出异常,此函数将无效 (强异常安全性保证)。
[编辑] 示例
以下代码使用 emplace_back
将 President
类型的对象附加到 std::list。它演示了 emplace_back
如何将参数转发给 President
构造函数,以及使用 emplace_back
如何避免使用 push_back 时所需的额外复制或移动操作。
运行此代码
#include <list> #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 << "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"; auto& ref = elections.emplace_back("Nelson Mandela", "South Africa", 1994); assert(ref.year == 1994 && "uses a reference to the created object (C++17)"); std::list<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"; }
输出
emplace_back: I am being constructed. push_back: I am being constructed. I am being moved. Contents: Nelson Mandela was elected president of South Africa in 1994. Franklin Delano Roosevelt was re-elected president of the USA in 1936.
[编辑] 另请参阅
将元素添加到末尾 (公共成员函数) | |
(C++11) |
就地构造元素 (公共成员函数) |