跳到主要内容

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

声明

C++17

void swap( variant& rhs ) noexcept(/* see below */);

C++20

constexpr void swap( variant& rhs ) noexcept(/* see below */);

交换两个 variant 对象。

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

除非类型 T_i 的左值可交换,并且对于 Types... 中的所有 T_istd::is_move_constructible_v<T_i> 为真,否则行为是未定义的。

参数

rhs - 要交换的 variant 对象。

返回值

(无)

异常

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

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

noexcept 规范

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

示例

#include <variant>
#include <string>
#include <iostream>

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

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

声明

C++17

void swap( variant& rhs ) noexcept(/* see below */);

C++20

constexpr void swap( variant& rhs ) noexcept(/* see below */);

交换两个 variant 对象。

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

除非类型 T_i 的左值可交换,并且对于 Types... 中的所有 T_istd::is_move_constructible_v<T_i> 为真,否则行为是未定义的。

参数

rhs - 要交换的 variant 对象。

返回值

(无)

异常

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

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

noexcept 规范

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

示例

#include <variant>
#include <string>
#include <iostream>

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