std::optional<T>::emplace
來自 cppreference.com
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) |