Namespaces
Variants

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

From cppreference.net

template < class ... Args >
void emplace_back ( Args && ... args ) ;
(C++17まで)
template < class ... Args >
reference emplace_back ( Args && ... args ) ;
(C++17以降)
(constexprはC++20以降)

コンテナの末尾に新しい要素を追加します。要素は std::allocator_traits::construct によって構築され、通常はプレースメント new を使用して、コンテナが提供する位置で要素をその場で構築します。引数 args... はコンストラクタに std:: forward < Args > ( args ) ... として転送されます。

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

目次

パラメータ

args - 要素のコンストラクタに転送する引数
型要件
-
以下のいずれかの条件が満たされる場合、動作は未定義です:

戻り値

(なし)

(C++17まで)

挿入された要素への参照。

(C++17以降)

計算量

償却定数時間。

例外

何らかの理由で例外がスローされた場合、この関数は何も効果を持ちません( 強い例外安全保証 )。 T のムーブコンストラクタが noexcept でなく、かつ CopyInsertable でない場合、 * this において、 vector は例外をスローするムーブコンストラクタを使用します。例外がスローされた場合、保証は放棄され、効果は未定義となります。

注記

再配置が発生する可能性があるため、 emplace_back は要素型が MoveInsertable であることを vector に対して要求します。

以下のコードは emplace_back を使用して President 型のオブジェクトを std::vector に追加します。 emplace_back がパラメータを President コンストラクタに転送する方法と、 emplace_back を使用することで push_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 (const President& president: elections)
        std::cout << president.name << " was elected president of "
                  << president.country << " in " << president.year << ".\n";
    for (const President& 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)
要素をその場で構築
(公開メンバ関数)