Namespaces
Variants

std:: exchange

From cppreference.net
Utilities library
헤더 파일에 정의됨 <utility>
template < class T, class U = T >
T exchange ( T & obj, U && new_value ) ;
(C++14부터)
(C++20부터 constexpr)
(C++23부터 조건부 noexcept)

obj 의 값을 new_value 로 교체하고 obj 의 이전 값을 반환합니다.

목차

매개변수

obj - 값을 대체할 객체
new_value - obj 에 할당할 값
타입 요구사항
-
T MoveConstructible 요구사항을 충족해야 합니다. 또한 U 타입 객체를 T 타입 객체로 이동 할당할 수 있어야 합니다.

반환값

obj 의 이전 값.

예외

(없음)

(C++23 이전)
(C++23 이후)

가능한 구현

template<class T, class U = T>
constexpr // C++20부터
T exchange(T& obj, U&& new_value)
    noexcept( // C++23부터
        std::is_nothrow_move_constructible<T>::value &&
        std::is_nothrow_assignable<T&, U>::value
    )
{
    T old_value = std::move(obj);
    obj = std::forward<U>(new_value);
    return old_value;
}

참고 사항

std::exchange move constructors 를 구현할 때와 special cleanup 이 필요하지 않은 멤버들에 대한 move assignment operators 를 구현할 때 사용할 수 있습니다:

struct S
{
    int n;
    S(S&& other) noexcept : n{std::exchange(other.n, 0)} {}
    S& operator=(S&& other) noexcept
    {
        n = std::exchange(other.n, 0); // n을 이동하면서 other.n에는 0을 남김
        // 참고: 자기 자신에 대한 이동 대입 연산 시 n은 변경되지 않음
        // 또한 참고: n이 특별한 정리 작업이 필요한 불투명한 리소스 핸들인 경우,
        //            리소스가 누출됨
        return *this;
    }
};
기능 테스트 매크로 표준 기능
__cpp_lib_exchange_function 201304L (C++14) std::exchange

예제

#include <iostream>
#include <iterator>
#include <utility>
#include <vector>
class stream
{
public:
    using flags_type = int;
public:
    flags_type flags() const { return flags_; }
    // flags_를 newf로 교체하고 이전 값을 반환합니다.
    flags_type flags(flags_type newf) { return std::exchange(flags_, newf); }
private:
    flags_type flags_ = 0;
};
void f() { std::cout << "f()"; }
int main()
{
    stream s;
    std::cout << s.flags() << '\n';
    std::cout << s.flags(12) << '\n';
    std::cout << s.flags() << "\n\n";
    std::vector<int> v;
    // 두 번째 템플릿 매개변수에 기본값이 있으므로
    // 중괄호 초기화 목록을 두 번째 인수로 사용할 수 있습니다. 아래 표현식은
    // std::exchange(v, std::vector<int>{1, 2, 3, 4})와 동일합니다.
    std::exchange(v, {1, 2, 3, 4});
    std::copy(begin(v), end(v), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << "\n\n";
    void (*fun)();
    // 템플릿 매개변수의 기본값은 일반 함수를
    // 두 번째 인수로 사용할 수 있게 합니다. 아래 표현식은
    // std::exchange(fun, static_cast<void(*)()>(f))와 동일합니다.
    std::exchange(fun, f);
    fun();
    std::cout << "\n\nFibonacci sequence: ";
    for (int a{0}, b{1}; a < 100; a = std::exchange(b, a + b))
        std::cout << a << ", ";
    std::cout << "...\n";
}

출력:

0
0
12
1, 2, 3, 4,
f()
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

참고 항목

두 객체의 값을 교환
(함수 템플릿)
원자적 객체의 값을 비원자적 인수로 원자적으로 교체하고 원자적 객체의 이전 값을 반환
(함수 템플릿)