std::list<T,Allocator>::emplace
来自 cppreference.cn
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) | |
(C++11) |
就地构造元素于结尾 (public member function) |