std::vector<T,Allocator>::emplace
來自 cppreference.com
template< class... Args > iterator emplace( const_iterator pos, Args&&... args ); |
(C++11 起) (C++20 起為 constexpr) |
|
在 pos 之前直接將一個新元素插入容器。
元素透過 std::allocator_traits::construct 構造,它通常使用放置 new 在容器提供的位置原地構造元素。然而,如果所需位置已被現有元素佔用,則插入的元素首先在另一個位置構造,然後移動賦值到所需位置。
引數 args... 被轉發給建構函式,作為 std::forward<Args>(args)...。 args... 可以直接或間接引用容器中的值。
如果在操作之後,新的 size()
大於舊的 capacity()
,則會發生重新分配,在這種情況下,所有迭代器(包括 end()
迭代器)以及對元素的所有引用都將失效。否則,只有插入點之前的迭代器和引用仍然有效。
目錄 |
[edit] 引數
pos | - | 新元素將被構造在其之前的迭代器 |
args | - | 轉發給元素建構函式的引數 |
型別要求 | ||
-T 必須滿足 可移動賦值 (MoveAssignable)、可移動插入 (MoveInsertable) 和 原地構造 (EmplaceConstructible) 的要求。 |
[edit] 返回值
指向已放置元素的迭代器。
[edit] 複雜度
與 pos 和 end() 之間的距離成線性關係。
[edit] 異常
如果丟擲異常,而不是由 T
的複製建構函式、移動建構函式、賦值運算子或移動賦值運算子丟擲,或者在 emplace
用於在末尾插入單個元素且 T
是 可複製插入 (CopyInsertable) 或非丟擲移動構造的情況下丟擲異常,則沒有影響(強異常保證)。
否則,效果未指定。
示例
執行此程式碼
#include <iostream> #include <string> #include <vector> struct A { std::string s; A(std::string str) : s(std::move(str)) { std::cout << " constructed\n"; } A(const A& o) : s(o.s) { std::cout << " copy constructed\n"; } A(A&& o) : s(std::move(o.s)) { std::cout << " move constructed\n"; } A& operator=(const A& other) { s = other.s; std::cout << " copy assigned\n"; return *this; } A& operator=(A&& other) { s = std::move(other.s); std::cout << " move assigned\n"; return *this; } }; int main() { std::vector<A> container; // reserve enough place so vector does not have to resize container.reserve(10); std::cout << "construct 2 times A:\n"; A two{"two"}; A three{"three"}; std::cout << "emplace:\n"; container.emplace(container.end(), "one"); std::cout << "emplace with A&:\n"; container.emplace(container.end(), two); std::cout << "emplace with A&&:\n"; container.emplace(container.end(), std::move(three)); std::cout << "content:\n"; for (const auto& obj : container) std::cout << ' ' << obj.s; std::cout << '\n'; }
輸出
construct 2 times A: constructed constructed emplace: constructed emplace with A&: copy constructed emplace with A&&: move constructed content: one two three
[edit] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2164 | C++11 | 不清楚引數是否可以引用容器 | 已明確 |
[edit] 參閱
插入元素 (public member function) | |
(C++11) |
就地構造元素於結尾 (public member function) |