名前空間
変種
操作

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

From cppreference.com
< cpp‎ | コンテナ‎ | deque
 
 
 
 
template< class... Args >
void emplace_back( Args&&... args );
(C++11以降)
(C++17まで)
template< class... Args >
reference emplace_back( Args&&... args );
(C++17以降)

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

すべてのイテレータ(end() イテレータを含む)は無効になります。参照は無効になりません。

目次

[編集] パラメータ

args - 要素のコンストラクタに転送する引数
型要件
-
T (コンテナの要素型) は、EmplaceConstructible の要件を満たす必要があります。

[編集] 戻り値

(なし)

(C++17まで)

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

(C++17以降)

[編集] 計算量

定数。

[編集] 例外

何らかの理由で例外がスローされた場合、この関数は効果がありません(強力な例外安全保証)。


[編集]

以下のコードはemplace_backを使用して、President型のオブジェクトをstd::dequeに追加します。emplace_backPresidentコンストラクタにパラメータを転送する方法を示し、emplace_backを使用すると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 (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)
要素を直接構築する
(公開メンバ関数) [編集]
English 日本語 中文(简体) 中文(繁體)