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 構造,該函式通常使用 placement-new 在容器提供的位置原地構造元素。引數 args... 作為 std::forward<Args>(args)... 轉發給建構函式。
迭代器或引用均未失效。
目錄 |
[編輯] 引數
args | - | 轉發給元素建構函式的引數 |
型別要求 | ||
-T (容器的元素型別) 必須滿足 EmplaceConstructible 的要求。 |
[編輯] 返回值
(無) |
(C++17 前) |
對插入元素的引用。 |
(C++17 起) |
[編輯] 複雜度
常數時間。
[編輯] 異常
如果由於任何原因丟擲異常,此函式無效果(強異常安全保證)。
[編輯] 示例
以下程式碼使用 emplace_back
向 std::list 後新增一個 President
型別的物件。它展示了 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.
[編輯] 參閱
新增元素到結尾 (public member function) | |
(C++11) |
就地構造元素 (public member function) |