std::optional<T>::emplace
From 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` が既に値を格納している場合、格納されている値はデストラクタを呼び出して破棄されます。
1) `args`... をパラメータとして、直接初期化(ただし、直接リスト初期化ではない)によって格納されている値を初期化します。
2) `ilist`, `args`... をパラメータとして、コンストラクタを呼び出して格納されている値を初期化します。このオーバーロードは、`std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value` が `true` である場合にのみ、オーバーロード解決に参加します。
目次 |
[編集] Parameters
| args... | - | コンストラクタに渡す引数 |
| ilist | - | コンストラクタに渡す初期化リスト |
| 型要件 | ||
| -オーバーロード (1) では、`T` は `Args...` から構築可能である必要があります。 | ||
| -オーバーロード (2) では、`T` は `std::initializer_list` および `Args...` から構築可能である必要があります。 | ||
[編集] Return value
新しく格納された値への参照。
[編集] Exceptions
選択された `T` のコンストラクタによってスローされる例外。
例外がスローされた場合、この呼び出しの後 `*this` は値を格納しません(もし以前に格納されていた値があっても、それは破棄されています)。| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__cpp_lib_optional |
202106L |
(C++20) (DR20) |
完全な `constexpr` (1,2) |
[編集] Example
このコードを実行
#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
[編集] Defect reports
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| P2231R1 | C++20 | C++20 では必要な操作が `constexpr` で可能であるにもかかわらず、`emplace` は `constexpr` ではありませんでした。 | constexprではありませんでした。 |
[編集] See also
| 内容を代入する (public member function) |