std::stack<T,Container>::emplace
来自cppreference.com
template<class... Args> void emplace( Args&&... args); | (C++11 起) (C++17 前) | |
template<class... Args> decltype(auto) emplace( Args&&... args); | (C++17 起) | |
推入新元素到栈顶。原位构造元素,即不进行移动或复制操作。以与提供给函数严格相同的实参调用元素的构造函数。
相当于调用 c.emplace_back(std::forward<Args>(args)...); 。
目录 |
[编辑]参数
args | - | 转发给元素构造函数的实参 |
[编辑]返回值
(无) | (C++17 前) |
上述对 Container::emplace_back 的调用返回的值或引用,若它存在。 | (C++17 起) |
[编辑]复杂度
与 Container::emplace_back 的复杂度相同。
[编辑]示例
运行此代码
#include <iostream>#include <stack> struct S {int id; S(int i, double d, std::string s): id{i}{std::cout<<"S::S("<< i <<", "<< d <<", \""<< s <<"\");\n";}}; int main(){std::stack<S> stack;const S& s = stack.emplace(42, 3.14, "C++");// 对于返回值 C++17 有此要求std::cout<<"id = "<< s.id<<'\n';}
输出:
S::S(42, 3.14, "C++") id = 42
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 2783 | C++17 | emplace 返回 reference ,破坏与 C++17 前容器的兼容性 | 返回 decltype(auto) |
[编辑]参阅
向栈顶插入元素 (公开成员函数) | |
移除栈顶元素 (公开成员函数) |