命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | container‎ | list
 
 
 
 
template< class... Args >
iterator emplace( const_iterator pos, Args&&... args );
(自 C++11 起)

在容器中 pos 前直接插入新元素。

元素通过 std::allocator_traits::construct 构造,它使用就地 new 在容器提供的位置就地构造元素。

实参 args...std::forward<Args>(args)... 的形式转发给构造函数。 args... 可以直接或间接引用容器中的值。

没有迭代器或引用会失效。

内容

[编辑] 参数

pos - 新元素将在其之前构造的迭代器
args - 转发给元素构造函数的参数
类型要求
-
T 必须满足 就地可构造 (EmplaceConstructible) 的要求。

[编辑] 返回值

指向被就地构造的元素的迭代器。

[编辑] 复杂度

常数。

[编辑] 异常

如果抛出异常(例如,由构造函数抛出),则容器保持不变,就像从未调用过此函数一样(强异常保证)。

示例

#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

[编辑] 缺陷报告

以下行为更改缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 应用于 发布时的行为 正确的行为
LWG 2164 C++11 尚不清楚参数是否可以引用容器 已明确

[编辑] 参见

插入元素
(公开成员函数) [编辑]
在末尾就地构造元素
(公开成员函数) [编辑]