名稱空間
變體
操作

std::optional<T>::swap

來自 cppreference.com
< cpp‎ | utility‎ | optional
 
 
 
 
void swap( optional& other ) noexcept(/* see below */);
(C++17 起)
(C++20 起為 constexpr)

交換與 other 的內容。

  • 如果 *thisother 均不含值,則函式無效果。
  • 如果 *thisother 中只有一個含值(我們稱這個物件為 in,另一個為 un),則 un 中包含的值透過 std::move(*in) 進行直接初始化,然後透過 in->T::~T() 銷燬 in 中包含的值。此呼叫後,in 不含值;un 含值。
  • 如果 *thisother 都含值,則透過呼叫 using std::swap; swap(**this, *other) 來交換包含的值。

除非型別 T可交換 (Swappable)std::is_move_constructible_v<T>true,否則程式是病態的。

目錄

[編輯] 引數

其他 - 要交換內容的 optional 物件

[編輯] 返回值

(無)

[編輯] 異常

noexcept 規範:  

如果丟擲異常,*thisother 中包含的值的狀態由型別 TswapT 的移動建構函式(以被呼叫者為準)的異常安全保證決定。對於 *thisother,如果物件包含值,則它在異常後仍然包含值,反之亦然。

特性測試 標準 特性
__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

[編輯] 參閱

特化 std::swap 演算法
(函式模板) [編輯]