std::optional<T>::swap

来自cppreference.com
< cpp‎ | utility‎ | optional
 
 
 
 
void swap( optional& other ) noexcept(/* 见下文 */);
(C++17 起)
(C++20 起为 constexpr)

other 交换内容。

  • *thisother 均不含值,则函数无效果。
  • *thisother 仅有一个含值(称此对象为 in,另一者为 un),则从 std::move(*in) 直接初始化 un 所含值,随后如同通过 in->T::~T() 析构 in 所含值。此调用后,in 不含值;un 含值。
  • *thisother 均含值,则通过调用 std::swap(**this, *other) 交换所含值。

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

目录

[编辑] 参数

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

[编辑] 返回值

(无)

[编辑] 异常

noexcept 说明:  

在抛异常的情况下,*thisother 所含值的状态由 TswapT 的移动构造函数的异常安全保证决定,取决于调用的是哪个。对于 *thisother,若对象含值,则令它继续含值,反之亦然。

[编辑] 注解

功能特性测试 标准 功能特性
__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 ? "交换前:\n" : "交换后:\n");
        std::cout << "opt1 含有 '" << opt1.value_or("") << "'\n";
        std::cout << "opt2 含有 '" << opt2.value_or("") << "'\n";
        std::cout << (e == Before ? "---SWAP---\n": "\n");
    };
 
    print_opts(Before);
    opt1.swap(opt2);
    print_opts(After);
 
    // 在仅一者含值时交换
    opt1 = "Lorem ipsum dolor sit amet, consectetur tincidunt.";
    opt2.reset();
 
    print_opts(Before);
    opt1.swap(opt2);
    print_opts(After);
}

输出:

交换前:
opt1 含有 'First example text'
opt2 含有 '2nd text'
---SWAP---
交换后:
opt1 含有 '2nd text'
opt2 含有 'First example text'
 
交换前:
opt1 含有 'Lorem ipsum dolor sit amet, consectetur tincidunt.'
opt2 含有 ''
---SWAP---
交换后:
opt1 含有 ''
opt2 含有 'Lorem ipsum dolor sit amet, consectetur tincidunt.'

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
P2231R1 C++20 swap 不是 constexpr 而要求的操作在 C++20 中能为 constexpr 使之为 constexpr

[编辑] 参阅

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