Namespaces
Variants

std::deque<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++26から)

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

すべてのイテレータ( end() イテレータを含む)が無効化されます。参照は無効化されません。

目次

パラメータ

args - 要素のコンストラクタに転送する引数
型要件
-
T EmplaceConstructible でない場合、 deque への args... からの構築は未定義動作となります。

戻り値

(なし)

(C++17まで)

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

(C++17以降)

計算量

定数。

例外

何らかの理由で例外がスローされた場合、この関数は何も効果を持ちません( strong exception safety guarantee )。

以下のコードは emplace_back を使用して President 型のオブジェクトを std::deque に追加します。 emplace_back がパラメータを President コンストラクタに転送する方法と、 push_back を使用した場合に必要な余分なコピーまたはムーブ操作を回避する方法を示しています。

#include <deque>
#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::deque<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::deque<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)
要素をその場で構築
(公開メンバ関数)