std::optional<T>::swap
來自 cppreference.com
void swap( optional& other ) noexcept(/* see below */); |
(C++17 起) (C++20 起為 constexpr) |
|
交換與 other 的內容。
- 如果 *this 和 other 均不含值,則函式無效果。
- 如果 *this 和 other 中只有一個含值(我們稱這個物件為
in
,另一個為un
),則un
中包含的值透過 std::move(*in) 進行直接初始化,然後透過 in->T::~T() 銷燬in
中包含的值。此呼叫後,in
不含值;un
含值。
- 如果 *this 和 other 都含值,則透過呼叫 using std::swap; swap(**this, *other) 來交換包含的值。
除非型別 T
為可交換 (Swappable) 且 std::is_move_constructible_v<T> 為 true,否則程式是病態的。
目錄 |
[編輯] 引數
其他 | - | 要交換內容的 optional 物件 |
[編輯] 返回值
(無)
[編輯] 異常
noexcept 規範:
noexcept(std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_swappable_v<T>)
std::is_nothrow_swappable_v<T>)
如果丟擲異常,*this 和 other 中包含的值的狀態由型別 T
的 swap
或 T
的移動建構函式(以被呼叫者為準)的異常安全保證決定。對於 *this 和 other,如果物件包含值,則它在異常後仍然包含值,反之亦然。
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_optional |
202106L |
(C++20) (DR20) |
完全 constexpr |
[編輯] 示例
執行此程式碼
#include <iostream> #include <optional> #include <string> int main() { std::optional<std::string> opt1("First example text"); std::optional<std::string> opt2("2nd text"); enum Swap { Before, After }; auto print_opts = [&](Swap e) { std::cout << (e == Before ? "Before swap:\n" : "After swap:\n"); std::cout << "opt1 contains '" << opt1.value_or("") << "'\n"; std::cout << "opt2 contains '" << opt2.value_or("") << "'\n"; std::cout << (e == Before ? "---SWAP---\n": "\n"); }; print_opts(Before); opt1.swap(opt2); print_opts(After); // Swap with only 1 set opt1 = "Lorem ipsum dolor sit amet, consectetur tincidunt."; opt2.reset(); print_opts(Before); opt1.swap(opt2); print_opts(After); }
輸出
Before swap: opt1 contains 'First example text' opt2 contains '2nd text' ---SWAP--- After swap: opt1 contains '2nd text' opt2 contains 'First example text' Before swap: opt1 contains 'Lorem ipsum dolor sit amet, consectetur tincidunt.' opt2 contains '' ---SWAP--- After swap: opt1 contains '' opt2 contains 'Lorem ipsum dolor sit amet, consectetur tincidunt.'
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
P2231R1 | C++20 | swap 不是 constexpr,而所需的運算在 C++20 中可以是 constexpr |
設為 constexpr |
[編輯] 參閱
(C++17) |
特化 std::swap 演算法 (函式模板) |