std::optional<T>:: emplace
|
template
<
class
...
Args
>
T & emplace ( Args && ... args ) ; |
(1) |
(seit C++17)
(constexpr seit C++20) |
|
template
<
class
U,
class
...
Args
>
T & emplace ( std:: initializer_list < U > ilist, Args && ... args ) ; |
(2) |
(seit C++17)
(constexpr seit C++20) |
Konstruiert den enthaltenen Wert direkt an Ort und Stelle. Falls * this vor dem Aufruf bereits einen Wert enthält, wird der enthaltene Wert durch Aufruf seines Destruktors zerstört.
Inhaltsverzeichnis |
Parameter
| args... | - | die an den Konstruktor zu übergebenden Argumente |
| ilist | - | die an den Konstruktor zu übergebende Initialisierungsliste |
| Typanforderungen | ||
-
T
muss von
Args...
konstruierbar sein für Überladung
(1)
|
||
-
T
muss von
std::initializer_list
und
Args...
konstruierbar sein für Überladung
(2)
|
||
Rückgabewert
Eine Referenz auf den neuen enthaltenen Wert.
Exceptions
Jede Ausnahme, die vom ausgewählten Konstruktor von
T
geworfen wird. Wenn eine Ausnahme geworfen wird,
*
this
enthält nach diesem Aufruf keinen Wert (der zuvor enthaltene Wert, falls vorhanden, wurde zerstört).
| Feature-Test Makro | Wert | Std | Funktion |
|---|---|---|---|
__cpp_lib_optional
|
202106L
|
(C++20)
(DR20) |
Vollständig constexpr ( 1,2 ) |
Beispiel
#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"; }
Ausgabe:
Assign: + constructed #0 + move constructed #1 ~ destructed #0 Emplace: ~ destructed #1 + constructed #2 End example ~ destructed #2
Fehlerberichte
Die folgenden verhaltensändernden Fehlerberichte wurden rückwirkend auf zuvor veröffentlichte C++-Standards angewendet.
| DR | Angewendet auf | Verhalten wie veröffentlicht | Korrigiertes Verhalten |
|---|---|---|---|
| P2231R1 | C++20 |
emplace
war nicht
constexpr
während die erforderlichen Operationen in C++20
constexpr
sein können
|
als constexpr festgelegt |
Siehe auch
|
weist Inhalte zu
(öffentliche Elementfunktion) |