命名空间
变体
操作

std::optional<T>::swap

来自 cppreference.cn
< cpp‎ | utility‎ | optional
 
 
 
 
void swap( optional& other ) noexcept(/* see below */);
(since C++17)
(constexpr since C++20)

other 的内容交换。

  • 如果 *thisother 都不含值,则此函数无效果。
  • 如果 *thisother 中仅有一个含值(称此对象为 in,另一个为 un),则 un 的内含值从 std::move(*in) 直接初始化,之后销毁 in 的内含值,如同通过 in->T::~T()。在此调用后,in 不含值;un 含值。
  • 如果 *thisother 均含值,则通过调用 using std::swap; swap(**this, *other) 交换内含值。

除非类型 T可交换 (Swappable)std::is_move_constructible_v<T>true,否则程序为非良构。

内容

[编辑] 参数

other - 要与其交换内容的 optional 对象

[编辑] 返回值

(无)

[编辑] 异常

noexcept 规范:  

在抛出异常的情况下,*thisother 的内含值的状态由类型 TswapT 的移动构造函数(调用了哪个就由哪个决定)的异常安全性保证决定。对于 *thisother 二者,如果对象原来含值,则调用后仍含值,反之亦然。

特性测试 Std 特性
__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);
 
    // Swap with only 1 set
    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++ 标准。

DR 应用于 发布时的行为 正确的行为
P2231R1 C++20 swap 在 C++20 中本可以为 constexpr,但当时不是 变为 constexpr

[编辑] 参见

特化 std::swap 算法
(函数模板) [编辑]