Namespaces
Variants

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

From cppreference.net

template < class ... Args >
iterator emplace ( const_iterator pos, Args && ... args ) ;
(C++11 起)
(C++26 起为 constexpr)

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

该元素通过 std::allocator_traits::construct 进行构造,通常使用定位 new 在容器提供的内存地址上就地构造元素。但若目标位置已被现有元素占用,则插入的元素会先在其它位置完成构造,随后通过移动赋值操作转入目标位置。

参数 args... 被作为 std:: forward < Args > ( args ) ... 转发给构造函数。 args... 可能直接或间接引用容器中的某个值。

所有迭代器(包括 end() 迭代器)均会失效。引用同样会失效,除非 pos == begin() pos == end() ,此时引用不会失效。

目录

参数

pos - 新元素将构造于其前的迭代器
args - 要转发给元素构造函数的参数
类型要求
-
若满足以下任一条件,则行为未定义:

返回值

指向被安置元素的迭代器。

复杂度

线性于 pos 与容器任一端点之间距离的较小值。

异常

若抛出的异常并非由 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

缺陷报告

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

缺陷报告 适用标准 发布时行为 正确行为
LWG 2164 C++11 未明确说明参数是否可引用容器 已明确说明

参见

插入元素
(公开成员函数)
在容器末尾原位构造元素
(公开成员函数)