std::optional<T>::swap
cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev ">
</tbody><tbody>
</tbody>
void swap( optional& other ) noexcept(/* */); |
( C++17) ( C++20) |
|
constexpr void swap( optional& other ) noexcept(/* */); |
( C++20) | |
other.
-
*this,other, .
-
*this,other,using std::swap; swap(**this, *other).Tlvalue Swappable.
, std::is_move_constructible_v<T> false.
| other | optional
|
()
noexcept:
noexcept(std::is_nothrow_move_constructible_v<T> && std::is_nothrow_swappable_v<T>) *this other swap T T, , . *this, other, , , .
#include <iostream>
#include <string>
#include <optional>
int main()
{
std::optional<std::string> opt1(" ");
std::optional<std::string> opt2("2- ");
enum Swap { Before, After };
auto print_opts = [&](Swap e) {
std::cout << (e == Before ? " :\n" : " :\n");
std::cout << "opt1 '" << opt1.value_or("") << "'\n";
std::cout << "opt2 '" << opt2.value_or("") << "'\n";
std::cout << (e == Before ? "------\n": "\n");
};
print_opts(Before);
opt1.swap(opt2);
print_opts(After);
// 1
opt1 = "Lorem ipsum dolor sit amet, consectetur tincidunt.";
opt2.reset();
print_opts(Before);
opt1.swap(opt2);
print_opts(After);
}
:
:
opt1 ' '
opt2 '2- '
------
:
opt1 '2- '
opt2 ' '
:
opt1 'Lorem ipsum dolor sit amet, consectetur tincidunt.'
opt2 ''
------
:
opt1 ''
opt2 'Lorem ipsum dolor sit amet, consectetur tincidunt.'
C++:
| WG | C++20 | swap constexpr, constexpr C++20 |
constexpr |
(C++17) |
std::swap ( ) |