std::swap(std::optional)
来自cppreference.com
在标头 <optional> 定义
|
||
template< class T > void swap( std::optional<T>& lhs, |
(C++17 起) (C++20 起为 constexpr ) |
|
对 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)))
注解
功能特性测试宏 | 值 | 标准 | 功能特性 |
---|---|---|---|
__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("起初:\t"); std::swap(a, b); print("swap(a, b):"); a.reset(); print("\n""a.reset():"); std::swap(a, b); print("swap(a, b):"); }
输出:
起初: 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 |
参阅
交换内容 (公开成员函数) |