名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 容器‎ | list
 
 
 
 
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... 可以直接或間接引用容器中的值。

迭代器或引用均未失效。

目錄

[edit] 引數

pos - 新元素將被構造在其之前的迭代器
args - 轉發給元素建構函式的引數
型別要求
-
T 必須滿足 EmplaceConstructible 的要求。

[edit] 返回值

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

[edit] 複雜度

常數時間。

[edit] 異常

如果丟擲異常(例如,由建構函式丟擲),容器保持未修改狀態,如同此函式從未被呼叫過一樣(強異常保證)。

示例

#include <iostream>
#include <string>
#include <list>
 
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::list<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] 參閱

插入元素
(public member function) [編輯]
就地構造元素於結尾
(public member function) [編輯]