命名空间
变体
操作

std::optional<T>::swap

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

交换与 other 的内容。

  • 如果 *thisother 均不含值,则函数无效果。
  • 如果 *thisother 中只有一个含值(我们称这个对象为 in,另一个为 un),则 un 中包含的值通过 std::move(*in) 进行直接初始化,然后通过 in->T::~T() 销毁 in 中包含的值。此调用后,in 不含值;un 含值。
  • 如果 *thisother 都含值,则通过调用 using std::swap; swap(**this, *other) 来交换包含的值。

除非类型 T可交换 (Swappable)std::is_move_constructible_v<T>true,否则程序是病态的。

目录

[编辑] 参数

其他 - 要交换内容的 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 ? "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++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
P2231R1 C++20 swap 不是 constexpr,而所需的运算在 C++20 中可以是 constexpr 设为 constexpr

[编辑] 参阅

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