Namespaces
Variants

std::optional<T>:: swap

From cppreference.net
Utilities library
void swap ( optional & other ) noexcept ( /* see below */ ) ;
(C++17以降)
(C++20以降constexpr)

内容を other の内容と交換します。

  • * this other の両方が値を保持していない場合、この関数は何も効果を持ちません。
  • this other のうち一方のみが値を保持している場合(このオブジェクトを in 、もう一方を un と呼ぶ)、 un の保持値は 直接初期化 され、その後 in の保持値は in - > T :: ~T ( ) によって破棄される。この呼び出し後、 in は値を保持せず、 un は値を保持する。
  • *thisとotherの両方が値を保持している場合、保持されている値は using std:: swap ; swap ( ** this, * other ) を呼び出すことで交換されます。

T Swappable であり、かつ std:: is_move_constructible_v < T > true でない限り、プログラムは不適格です。

目次

パラメータ

other - 内容を交換する対象の optional オブジェクト

戻り値

(なし)

例外

例外がスローされた場合、 * 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);
    // 1つのみ設定された状態でのスワップ
    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++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
P2231R1 C++20 swap constexpr ではなかったが、必要な操作はC++20で constexpr 化可能 constexpr 化された

関連項目

std::swap アルゴリズムを特殊化する
(関数テンプレート)