std::list<T,Allocator>:: emplace
|
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... 可能直接或间接引用容器中的某个值。
不会使任何迭代器或引用失效。
目录参数
返回值指向被安置元素的迭代器。 复杂度常量。 异常如果抛出异常(例如由构造函数抛出),容器将保持未修改状态,如同此函数从未被调用过(强异常保证)。 示例
运行此代码
#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++标准。
参见
| ||||||||||||||||||||||||