命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | utility‎ | variant
 
 
 
 
void swap( variant& rhs ) noexcept(/* 参见下方 */);
(since C++17)
(constexpr since C++20)

交换两个 variant 对象。

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

除非类型 T_i可交换 (Swappable)std::is_move_constructible_v<T_i>true,否则程序是非良构的,这对于 Types... 中的所有 T_i 成立。

目录

[编辑] 参数

rhs - 要与之交换的 variant 对象

[编辑] 返回值

(无)

[编辑] 异常

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

否则,可能抛出 *thisrhs 当前持有的备选项的移动构造函数抛出的任何异常。

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

[编辑] 注解

特性测试 Std 特性
__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 算法
(函数模板) [编辑]