std::variant<Types...>::swap
來自 cppreference.com
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
不為 可交換 (Swappable) 且對於 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>) && ...))
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 | 在 C++20 中,constexpr 可以有非平凡的解構函式,但 swap 不是 constexpr |
設為 constexpr |
[編輯] 參閱
(C++17) |
特化 std::swap 演算法 (函式模板) |