名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 容器‎ | deque
 
 
 
 
template< class... Args >
iterator emplace( const_iterator pos, Args&&... args );
(C++11 起)

pos 之前直接將一個新元素插入容器。

元素透過 std::allocator_traits::construct 構造,它通常使用 placement new 在容器提供的位置原地構造元素。然而,如果所需位置已被現有元素佔據,則插入的元素首先在另一個位置構造,然後移動賦值到所需位置。

引數 args... 被轉發給建構函式,作為 std::forward<Args>(args)...args... 可以直接或間接引用容器中的值。

所有迭代器(包括 end() 迭代器)都會失效。引用也會失效,除非 pos == begin()pos == end(),在這種情況下它們不會失效。

目錄

[edit] 引數

pos - 新元素將被構造在其之前的迭代器
args - 轉發給元素建構函式的引數
型別要求
-
T 必須滿足 可移動賦值 (MoveAssignable)可移動插入 (MoveInsertable)原地構造 (EmplaceConstructible) 的要求。

[edit] 返回值

指向已放置元素的迭代器。

[edit] 複雜度

pos 與容器任一端點之間距離的較小者中呈線性。

[edit] 異常

如果丟擲的異常不是由 T 的複製建構函式、移動建構函式、賦值運算子或移動賦值運算子丟擲的,或者如果在使用 emplace 在任一端插入單個元素時丟擲異常,則無副作用(強異常保證)。

否則,效果未指定。

示例

#include <iostream>
#include <string>
#include <deque>
 
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::deque<A> container;
 
    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

[edit] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2164 C++11 不清楚引數是否可以引用容器 已明確

[edit] 參閱

插入元素
(公共成員函式) [編輯]
就地構造元素於結尾
(公共成員函式) [編輯]