Namespaces
Variants

std::optional<T>:: swap

From cppreference.net
Utilities library
void swap ( optional & other ) noexcept ( /* see below */ ) ;
(自 C++17 起)
(自 C++20 起为 constexpr)

other 交换内容。

  • 如果 * this other 均不包含值,则该函数不产生任何效果。
  • 如果仅有一个对象( * this other )包含值(称该对象为 in ,另一个为 un ),则使用 std :: move ( * in ) un 的所含值进行 直接初始化 ,随后如同通过 in - > T :: ~T ( ) 销毁 in 的所含值。此调用后, in 不再包含值; un 包含值。
  • * this other 均包含值,则通过调用 using std:: swap ; swap ( ** this, * other ) 交换所包含的值。

除非类型 T 满足 可交换 要求且 std:: is_move_constructible_v < T > true ,否则程序非良构。

目录

参数

其他 - 用于交换内容的 optional 对象

返回值

(无)

异常

在抛出异常的情况下, * 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);
    // 仅设置一个 optional 时的交换
    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

参见

特化 std::swap 算法
(函数模板)