std::variant<Types...>::swap
来自cppreference.com
void swap( variant& rhs ) noexcept(/* 见下文 */); |
(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()
。若抛出了异常,则值的状态取决于被调用交换函数的异常安全性; - 否则,交换 rhs 与 *this 的值。若抛出了异常,则 *this 与 rhs 的状态取决于变体的移动构造函数的异常安全性。
除非对于所有 Types...
中的 T_i
,T_i
左值可交换 (Swappable) 且 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>) && ...))
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++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
P2231R1 | C++20 | swap 不是 constexpr,而非平凡析构函数在 C++20 中能为 constexpr
|
使之为 constexpr |