|
|
Member functions | ||||
Observers | ||||
Iterators | ||||
(C++26) | ||||
(C++26) | ||||
Monadic operations | ||||
(C++23) | ||||
(C++23) | ||||
(C++23) | ||||
Modifiers | ||||
Non-member functions | ||||
swap(std::optional) | ||||
Deduction guides | ||||
Helper classes | ||||
Helper objects | ||||
Defined in header <optional> | ||
template<class T> void swap(std::optional<T>& lhs, | (since C++17) (constexpr since C++20) | |
Overloads thestd::swap algorithm forstd::optional. Exchanges the state oflhs with that ofrhs. Effectively callslhs.swap(rhs).
This overload participates in overload resolution only ifstd::is_move_constructible_v<T> andstd::is_swappable_v<T> are bothtrue.
Contents |
lhs, rhs | - | optional objects whose states to swap |
(none)
Feature-test macro | Value | Std | Feature |
---|---|---|---|
__cpp_lib_optional | 202106L | (C++20) (DR20) | Fullyconstexpr |
#include <iostream>#include <optional>#include <string> int main(){std::optional<std::string> a{"██████"}, b{"▒▒▒▒▒▒"}; auto print=[&](autoconst& s){std::cout<< s<<"\t""a = "<< a.value_or("(null)")<<" ""b = "<< b.value_or("(null)")<<'\n';}; print("Initially:");std::swap(a, b); print("swap(a, b):"); a.reset(); print("\n""a.reset():");std::swap(a, b); print("swap(a, b):");}
Output:
Initially: a = ██████ b = ▒▒▒▒▒▒swap(a, b): a = ▒▒▒▒▒▒ b = ██████ a.reset(): a = (null) b = ██████swap(a, b): a = ██████ b = (null)
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
P2231R1 | C++20 | swap was notconstexpr while the required operations can beconstexpr in C++20 | madeconstexpr |
exchanges the contents (public member function)[edit] |