Namespaces
Variants

std::vector<T,Allocator>:: emplace

From cppreference.net

template < class ... Args >
iterator emplace ( const_iterator pos, Args && ... args ) ;
(C++11以降)
(constexpr C++20以降)

コンテナに新しい要素を pos の直前に直接挿入します。

要素は std::allocator_traits::construct を通じて構築されます。これは通常、配置 new を使用して、コンテナが提供する位置で要素をその場で構築します。ただし、必要な位置が既存の要素によって占有されている場合、挿入される要素は最初に別の場所で構築され、その後必要な位置にムーブ代入されます。

引数 args... はコンストラクタに std:: forward < Args > ( args ) ... として転送されます。 args... はコンテナ内の値に直接または間接的に参照している可能性があります。

操作後に新しい size() が古い capacity() を超える場合、再割り当てが発生し、その場合すべてのイテレータ( end() イテレータを含む)と要素へのすべての参照が無効化されます。それ以外の場合、挿入ポイントより前のイテレータと参照のみが有効なままです。

目次

パラメータ

pos - 新しい要素が構築される位置の前を指すイテレータ
args - 要素のコンストラクタに転送される引数
型要件
-
以下のいずれかの条件が満たされる場合、動作は未定義です:

戻り値

配置された要素を指すイテレータ。

計算量

pos end() の間の距離に対して線形。

例外

T のコピーコンストラクタ、ムーブコンストラクタ、代入演算子、またはムーブ代入演算子以外で例外がスローされた場合、あるいは末尾に単一要素を挿入するために emplace が使用されている間に例外がスローされ、かつ T CopyInsertable またはnothrow move constructibleである場合、効果はありません(強い例外保証)。

それ以外の場合、効果は未指定です。

#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;
    // ベクターのリサイズが不要な十分な領域を確保
    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

不具合報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 2164 C++11 引数がコンテナを参照できるかどうかが不明確であった 明確化された

関連項目

要素を挿入する
(公開メンバ関数)
要素をその場で末尾に構築する
(公開メンバ関数)