std::swap(std::optional)
来自 cppreference.cn
定义于头文件 <optional> |
||
template< class T > void swap( std::optional<T>& lhs, |
(C++17 起) (C++20 起为 constexpr) |
|
重载 std::swap 算法,用于 std::optional。交换 lhs 和 rhs 的状态。实际上调用 lhs.swap(rhs)。
此重载仅在 std::is_move_constructible_v<T> 和 std::is_swappable_v<T> 都为 true 时才参与重载决议。
目录 |
[编辑] 参数
lhs, rhs | - | 要交换状态的 optional 对象 |
[编辑] 返回值
(无)
[编辑] 异常
noexcept 规范:
noexcept(noexcept(lhs.swap(rhs)))
[编辑] 注解
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_lib_optional |
202106L |
(C++20) (DR20) |
完全 constexpr |
[编辑] 示例
运行此代码
#include <iostream> #include <optional> #include <string> int main() { std::optional<std::string> a{"██████"}, b{"▒▒▒▒▒▒"}; auto print = [&](auto const& 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):"); }
输出
Initially: a = ██████ b = ▒▒▒▒▒▒ swap(a, b): a = ▒▒▒▒▒▒ b = ██████ a.reset(): a = (null) b = ██████ swap(a, b): a = ██████ b = (null)
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
P2231R1 | C++20 | swap 不是 constexpr,而所需的运算在 C++20 中可以是 constexpr |
设为 constexpr |
[编辑] 参阅
交换内容 (public member function) |