名稱空間
變體
操作

std::optional<T>::emplace

來自 cppreference.com
< cpp‎ | utility‎ | optional
 
 
 
 
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&&...>::valuetrue 時參與過載決議。

目錄

[編輯] 引數

args... - 要傳遞給建構函式的引數
ilist - 要傳遞給建構函式的初始化列表
型別要求
-
對於過載 (1)T 必須可由 Args... 構造。
-
對於過載 (2)T 必須可由 std::initializer_listArgs... 構造。

[編輯] 返回值

對新包含值的引用。

[編輯] 異常

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) [編輯]