std::vector<T,Allocator>::emplace_back
template< class... Args > void emplace_back( Args&&... args ); |
(C++11以降) (C++17まで) |
|
| template< class... Args > reference emplace_back( Args&&... args ); |
(C++17以降) (C++20 以降 constexpr) |
|
コンテナの末尾に新しい要素を追加します。要素は std::allocator_traits::construct を通して構築され、通常は配置 new を使用してコンテナが提供する場所に要素をインプレースで構築します。引数 args... は、std::forward<Args>(args)... としてコンストラクタに転送されます。
操作後、新しい size() が古い capacity() より大きい場合、再割り当てが行われ、その場合、すべてのイテレータ ( end() イテレータを含む) と要素へのすべての参照は無効になります。それ以外の場合、 end() イテレータのみが無効になります。
目次 |
[編集] パラメータ
| args | - | 要素のコンストラクタに転送する引数 |
| 型要件 | ||
-T (コンテナの要素型) は、MoveInsertable および EmplaceConstructible の要件を満たす必要があります。 | ||
[編集] 戻り値
|
(なし) |
(C++17まで) |
|
挿入された要素への参照。 |
(C++17以降) |
[編集] 計算量
償却定数。
[編集] 例外
何らかの理由で例外がスローされた場合、この関数は効果を持ちません(強力な例外安全性保証)。T のムーブコンストラクタが noexcept ではなく、かつ *this に CopyInsertable でもない場合、vector は例外をスローするムーブコンストラクタを使用します。これがスローする場合、保証は無効になり、効果は未定義となります。
注釈
再割り当てが発生する可能性があるため、emplace_back は要素型にベクター用の MoveInsertable であることを要求します。
[編集] 例
以下のコードは、President 型のオブジェクトを std::vector に追加するために emplace_back を使用しています。これは、emplace_back がパラメータを President コンストラクタに転送する方法を示しており、push_back を使用する場合に必要な余分なコピーまたはムーブ操作を emplace_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 << "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::vector<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::vector<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) |
要素を直接構築する (公開メンバ関数) |