[ Web Proxy ]
URL:
Viewing: https://ru.cppreference.com/cpp/utility/optional/swap [Back]  [Original]

std::optional<T>::swap cppreference.com
cppreference.com

std::optional<T>::swap

cppreference.com
 
C++
(C++20)
(C++20)
(C++11)
(C++20)
/
(C++11)
(C++11)
(C++11)
(C++17)
 
 
 
<tbody> </tbody> <tbody class="t-dcl-rev "> </tbody><tbody> </tbody>
void swap( optional& other ) noexcept(/* */);
( C++17)
( C++20)
constexpr void swap( optional& other ) noexcept(/* */);
( C++20)

other.

  • *this, other , .
  • *this other ( in, un), un std::move(*in), in , in->T::~T(). in ; un .
  • *this, other , using std::swap; swap(**this, *other). T lvalue Swappable.

, std::is_move_constructible_v<T> false.

other optional

()

noexcept:  
noexcept(std::is_nothrow_move_constructible_v<T> && std::is_nothrow_swappable_v<T>)

*this other swap T T, , . *this, other, , , .

#include <iostream>
#include <string>
#include <optional>

int main()
{
    std::optional<std::string> opt1("  ");
    std::optional<std::string> opt2("2- ");

    enum Swap { Before, After };
    auto print_opts = [&](Swap e) {
        std::cout << (e == Before ? " :\n" : " :\n");
        std::cout << "opt1  '" << opt1.value_or("") << "'\n";
        std::cout << "opt2  '" << opt2.value_or("") << "'\n";
        std::cout << (e == Before ? "------\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);
}

:

 :
opt1  '  '
opt2  '2- '
------
 :
opt1  '2- '
opt2  '  '

 :
opt1  'Lorem ipsum dolor sit amet, consectetur tincidunt.'
opt2  ''
------
 :
opt1  ''
opt2  'Lorem ipsum dolor sit amet, consectetur tincidunt.'

C++:

WG C++20 swap constexpr,
constexpr C++20
constexpr

std::swap
( ) []

Web Proxy Viewer  |  New URL  |  Original Page