std::optional<T>::swap
来自cppreference.com
void swap( optional& other ) noexcept(/* 见下文 */); |
(C++17 起) (C++20 起为 constexpr ) |
|
与 other 交换内容。
- 若 *this 和 other 均不含值,则函数无效果。
- 若 *this 与 other 仅有一个含值(称此对象为
in
,另一者为un
),则从 std::move(*in) 直接初始化un
所含值,随后如同通过 in->T::~T() 析构in
所含值。此调用后,in
不含值;un
含值。
- 若 *this 与 other 均含值,则通过调用 std::swap(**this, *other) 交换所含值。
T
的左值必须满足可交换 (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>)
std::is_nothrow_swappable_v<T>)
在抛异常的情况下,*this 和 other 所含值的状态由 T
的 swap
或 T
的移动构造函数的异常安全保证决定,取决于调用的是哪个。对于 *this 和 other,若对象含值,则令它继续含值,反之亦然。
注解
功能特性测试宏 | 值 | 标准 | 功能特性 |
---|---|---|---|
__cpp_lib_optional |
202106L | (C++20) (DR20) |
完全 constexpr |
示例
运行此代码
#include <iostream> #include <optional> #include <string> int main() { std::optional<std::string> opt1("First example text"); std::optional<std::string> opt2("2nd text"); 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 ? "---SWAP---\n": "\n"); }; print_opts(Before); opt1.swap(opt2); print_opts(After); // 在仅一者含值时交换 opt1 = "Lorem ipsum dolor sit amet, consectetur tincidunt."; opt2.reset(); print_opts(Before); opt1.swap(opt2); print_opts(After); }
输出:
交换前: opt1 含有 'First example text' opt2 含有 '2nd text' ---SWAP--- 交换后: opt1 含有 '2nd text' opt2 含有 'First example text' 交换前: opt1 含有 'Lorem ipsum dolor sit amet, consectetur tincidunt.' opt2 含有 '' ---SWAP--- 交换后: opt1 含有 '' opt2 含有 'Lorem ipsum dolor sit amet, consectetur tincidunt.'
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
P2231R1 | C++20 | swap 不是 constexpr 而要求的操作在 C++20 中能为 constexpr
|
使之为 constexpr |
参阅
(C++17) |
特化 std::swap 算法 (函数模板) |