Namespaces
Variants

std::variant<Types...>:: swap

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

交换两个 variant 对象。

  • * this rhs 均因异常而无值,则不执行任何操作。
  • 否则,若 * this rhs 持有相同备选类型,则调用 swap ( * std:: get_if < i > ( this ) , * std:: get_if < i > ( std:: addressof ( rhs ) ) ) ,其中 i index() 。若抛出异常,值的状态取决于所调用 swap 函数的异常安全性。
  • 否则,交换 rhs * this 的值。若抛出异常, * this rhs 的状态取决于 variant 移动构造函数的异常安全性。

除非所有类型 T_i 均满足 可交换 要求,且对所有 Types... 中的 T_i 均有 std:: is_move_constructible_v < T_i > true ,否则程序非良构。

目录

参数

rhs - 用于交换的 variant 对象

返回值

(无)

异常

如果 this - > index ( ) == rhs. index ( ) ,可能抛出由 swap ( * std:: get_if < i > ( this ) , * std:: get_if < i > ( std:: addressof ( rhs ) ) ) 抛出的任何异常,其中 i index()

否则,可能抛出当前由 * this rhs 持有的备选类型的移动构造函数所抛出的任何异常。

noexcept 规范:
noexcept ( ( ( std:: is_nothrow_move_constructible_v < Types > &&
std:: is_nothrow_swappable_v < Types > ) && ... ) )

注释

功能测试 标准 功能特性
__cpp_lib_variant 202106L (C++20)
(DR)
完全 constexpr 化的 std::variant

示例

#include <iostream>
#include <string>
#include <variant>
int main()
{
    std::variant<int, std::string> v1{2}, v2{"abc"};
    std::visit([](auto&& x) { std::cout << x << ' '; }, v1);
    std::visit([](auto&& x) { std::cout << x << '\n'; }, v2);
    v1.swap(v2);
    std::visit([](auto&& x) { std::cout << x << ' '; }, v1);
    std::visit([](auto&& x) { std::cout << x << '\n'; }, v2);
}

输出:

2 abc
abc 2

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 适用范围 发布时的行为 正确行为
P2231R1 C++20 swap 不是 constexpr ,而 C++20 中非平凡析构函数可以是 constexpr 改为 constexpr

参阅

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