Namespaces
Variants

std:: swap (std::optional)

From cppreference.net
Utilities library
定义于头文件 <optional>
template < class T >

void swap ( std:: optional < T > & lhs,

std:: optional < T > & rhs ) noexcept ( /* see below */ ) ;
(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("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

另请参阅

交换内容
(公开成员函数)