std::optional<T>::swap
来自 cppreference.cn
void swap( optional& other ) noexcept(/* see below */); |
(C++17 起) (C++20 起为 constexpr) |
|
交换与 other 的内容。
- 如果 *this 和 other 均不含值,则函数无效果。
- 如果 *this 和 other 中只有一个含值(我们称这个对象为
in
,另一个为un
),则un
中包含的值通过 std::move(*in) 进行直接初始化,然后通过 in->T::~T() 销毁in
中包含的值。此调用后,in
不含值;un
含值。
- 如果 *this 和 other 都含值,则通过调用 using std::swap; swap(**this, *other) 来交换包含的值。
除非类型 T
为可交换 (Swappable) 且 std::is_move_constructible_v<T> 为 true,否则程序是病态的。
目录 |
[编辑] 参数
其他 | - | 要交换内容的 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 ? "Before swap:\n" : "After swap:\n"); std::cout << "opt1 contains '" << opt1.value_or("") << "'\n"; std::cout << "opt2 contains '" << opt2.value_or("") << "'\n"; std::cout << (e == Before ? "---SWAP---\n": "\n"); }; print_opts(Before); opt1.swap(opt2); print_opts(After); // Swap with only 1 set opt1 = "Lorem ipsum dolor sit amet, consectetur tincidunt."; opt2.reset(); print_opts(Before); opt1.swap(opt2); print_opts(After); }
输出
Before swap: opt1 contains 'First example text' opt2 contains '2nd text' ---SWAP--- After swap: opt1 contains '2nd text' opt2 contains 'First example text' Before swap: opt1 contains 'Lorem ipsum dolor sit amet, consectetur tincidunt.' opt2 contains '' ---SWAP--- After swap: opt1 contains '' opt2 contains 'Lorem ipsum dolor sit amet, consectetur tincidunt.'
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
P2231R1 | C++20 | swap 不是 constexpr,而所需的运算在 C++20 中可以是 constexpr |
设为 constexpr |
[编辑] 参阅
(C++17) |
特化 std::swap 算法 (函数模板) |