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 의 포함된 값은 std :: move ( * in ) 로부터 직접 초기화 되며, 이어서 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);
    // 하나만 설정된 상태에서 교환
    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 알고리즘을 특수화함
(함수 템플릿)