命名空间
变体
操作

std::optional<T>::emplace

来自 cppreference.cn
< cpp‎ | utility‎ | optional
 
 
 
 
template< class... Args >
T& emplace( Args&&... args );
(1) (since C++17)
(constexpr since C++20)
template< class U, class... Args >
T& emplace( std::initializer_list<U> ilist, Args&&... args );
(2) (since C++17)
(constexpr since C++20)

就地构造所含值。如果 *this 在调用前已包含值,则会调用其析构函数销毁所含值。

1) 通过使用 std::forward<Args>(args)... 作为参数进行直接初始化 (但不是直接列表初始化) 来初始化所含值。
2) 通过使用 ilist, std::forward<Args>(args)... 作为参数调用其构造函数来初始化所含值。仅当 std::is_constructible<T, std::initializer_list<U>&, Args&&...>::valuetrue 时,此重载才参与重载解析。

内容

[edit] 参数

args... - 传递给构造函数的参数
ilist - 传递给构造函数的初始化列表
类型要求
-
T 必须可从 Args... 构造 (对于重载 (1))
-
T 必须可从 std::initializer_listArgs... 构造 (对于重载 (2))

[edit] 返回值

对新包含值的引用。

[edit] 异常

T 的选定构造函数抛出的任何异常。如果抛出异常,则 *this 在此调用后不包含值(先前包含的值(如果有)已被销毁)。

特性测试 Std 特性
__cpp_lib_optional 202106L (C++20)
(DR20)
完全 constexpr (1,2)

[edit] 示例

#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

[edit] 缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
P2231R1 C++20 emplace 在 C++20 中本可以为 constexpr 时却不是 constexpr 已设为 constexpr

[edit] 参见

赋值内容
(公共成员函数) [编辑]