std::list<T,Allocator>::emplace
From cppreference.com
| template< class... Args > iterator emplace( const_iterator pos, Args&&... args ); |
(C++11以降) | |
pos の直前に新しい要素を直接挿入します。
要素は、コンテナが提供する場所で、配置newを使用して要素をインプレースで構築するstd::allocator_traits::constructを通じて構築されます。
args... 引数は、std::forward<Args>(args)... としてコンストラクタに転送されます。args... は、コンテナ内の値に直接的または間接的に参照することができます。
イテレータや参照は無効化されない。
目次 |
[編集] パラメータ
| pos | - | 新しい要素が構築される直前のイテレータ |
| args | - | 要素のコンストラクタに転送する引数 |
| 型要件 | ||
-T は EmplaceConstructible の要件を満たす必要があります。 | ||
[編集] 戻り値
挿入された要素を指すイテレータ。
[編集] 計算量
定数。
[編集] 例外
例外がスローされた場合(例:コンストラクタによる)、コンテナは変更されず、この関数が呼び出されなかったかのようになります(強力な例外安全性)。
例
このコードを実行
#include <iostream> #include <string> #include <list> 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::list<A> container; 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
[編集] 不具合報告
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 2164 | C++11 | 引数がコンテナを参照できるかどうかは不明でした | 明確化された |
[編集] 関連項目
| 要素を挿入する (公開メンバ関数) | |
| (C++11) |
末尾に要素を直接構築する (公開メンバ関数) |