std::swap(std::optional)
来自 cppreference.cn
定义于头文件 <optional> |
||
template< class T > void swap( std::optional<T>& lhs, |
(since C++17) (constexpr since C++20) |
|
为 std::optional 重载 std::swap 算法。交换 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)))
[编辑] 注解
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
P2231R1 | C++20 | swap 在 C++20 中不是 constexpr,而所需操作可以是 constexpr | 已变为 constexpr |
[编辑] 参见
交换内容 (public member function) |