Namespaces
Variants

std::optional<T>:: emplace

From cppreference.net
Utilities library
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 已包含值,则通过调用其析构函数销毁所含值。

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

目录

参数

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

返回值

对新包含值的引用。

异常

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";
    // 由于opt已包含值,此处也会销毁该值
    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 emplace 不是 constexpr ,而所需操作在 C++20 中可以是 constexpr 改为 constexpr

参见

赋值内容
(公开成员函数)