std::swap(std::optional)
來自 cppreference.com
定義於標頭檔案 <optional> |
||
template< class T > void swap( std::optional<T>& lhs, |
(C++17 起) (C++20 起為 constexpr) |
|
過載 std::swap 演算法,用於 std::optional。交換 lhs 和 rhs 的狀態。實際上呼叫 lhs.swap(rhs)。
此過載僅在 std::is_move_constructible_v<T> 和 std::is_swappable_v<T> 都為 true 時才參與過載決議。
目錄 |
[編輯] 引數
lhs, rhs | - | 要交換狀態的 optional 物件 |
[編輯] 返回值
(無)
[編輯] 異常
noexcept 規範:
noexcept(noexcept(lhs.swap(rhs)))
[編輯] 註解
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_optional |
202106L |
(C++20) (DR20) |
完全 constexpr |
[編輯] 示例
執行此程式碼
#include <iostream> #include <optional> #include <string> int main() { std::optional<std::string> a{"██████"}, b{"▒▒▒▒▒▒"}; auto print = [&](auto const& s) { std::cout << s << "\t" "a = " << a.value_or("(null)") << " " "b = " << b.value_or("(null)") << '\n'; }; print("Initially:"); std::swap(a, b); print("swap(a, b):"); a.reset(); print("\n""a.reset():"); std::swap(a, b); print("swap(a, b):"); }
輸出
Initially: a = ██████ b = ▒▒▒▒▒▒ swap(a, b): a = ▒▒▒▒▒▒ b = ██████ a.reset(): a = (null) b = ██████ swap(a, b): a = ██████ b = (null)
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
P2231R1 | C++20 | swap 不是 constexpr,而所需的運算在 C++20 中可以是 constexpr |
設為 constexpr |
[編輯] 參閱
交換內容 (public member function) |