Namespaces
Variants

std:: swap (std::optional)

From cppreference.net
Utilities library
헤더 파일에 정의됨 <optional>
template < class T >

void swap ( std:: optional < T > & lhs,

std:: optional < T > & rhs ) noexcept ( /* see below */ ) ;
(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++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
P2231R1 C++20 swap 함수가 constexpr 가 아니었으나, C++20에서 요구되는 연산들이 constexpr 일 수 있음 constexpr 로 변경됨

참고 항목

내용을 교환합니다
(public member function)