std::optional<T>::emplace
来自 cppreference.cn
template< class... Args > T& emplace( Args&&... args ); |
(1) | (C++17 起) (C++20 起为 constexpr) |
template< class U, class... Args > T& emplace( std::initializer_list<U> ilist, Args&&... args ); |
(2) | (C++17 起) (C++20 起为 constexpr) |
就地构造包含值。如果调用前 *this 已包含值,则通过调用其析构函数销毁该包含值。
2) 通过调用其构造函数初始化包含值,参数为 ilist, std::forward<Args>(args)...。此重载仅在 std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value 为 true 时参与重载决议。
目录 |
[编辑] 参数
args... | - | 要传递给构造函数的参数 |
ilist | - | 要传递给构造函数的初始化列表 |
类型要求 | ||
-对于重载 (1),T 必须可由 Args... 构造。 | ||
-对于重载 (2),T 必须可由 std::initializer_list 和 Args... 构造。 |
[编辑] 返回值
对新包含值的引用。
[编辑] 异常
由 T
的选定构造函数抛出的任何异常。如果抛出异常,则此调用后 *this 不包含值(如果之前包含值,则已被销毁)。
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_lib_optional |
202106L |
(C++20) (DR20) |
完全 constexpr (1,2) |
[编辑] 示例
运行此代码
#include <iostream> #include <optional> struct A { std::string s; A(std::string str) : s(std::move(str)), id{n++} { note("+ constructed"); } ~A() { note("~ destructed"); } A(const A& o) : s(o.s), id{n++} { note("+ copy constructed"); } A(A&& o) : s(std::move(o.s)), id{n++} { note("+ move constructed"); } A& operator=(const A& other) { s = other.s; note("= copy assigned"); return *this; } A& operator=(A&& other) { s = std::move(other.s); note("= move assigned"); return *this; } inline static int n{}; int id{}; void note(auto s) { std::cout << " " << s << " #" << id << '\n'; } }; int main() { std::optional<A> opt; std::cout << "Assign:\n"; opt = A("Lorem ipsum dolor sit amet, consectetur adipiscing elit nec."); std::cout << "Emplace:\n"; // As opt contains a value it will also destroy that value opt.emplace("Lorem ipsum dolor sit amet, consectetur efficitur."); std::cout << "End example\n"; }
输出
Assign: + constructed #0 + move constructed #1 ~ destructed #0 Emplace: ~ destructed #1 + constructed #2 End example ~ destructed #2
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
P2231R1 | C++20 | 在 C++20 中,虽然所需的运算可以是 constexpr,但 emplace 不是 constexpr。 |
设为 constexpr |
[编辑] 参阅
赋值内容 (public member function) |