命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | container‎ | 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(),在这种情况下它们不会失效。

目录

[编辑] 参数

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

[编辑] 返回值

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

[编辑] 复杂度

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++ 标准。

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

[编辑] 参见

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