utility_exchange

utility_exchange (std::exchange 함수)

이 페이지는 C++ 표준 라이브러리의 std::exchange 함수에 대해 설명해요. std::exchange는 객체의 값을 새 값으로 교체하고, 교체하기 전의 값을 반환하는 유틸리티 함수예요. C++14부터 사용할 수 있으며, C++20에서 constexpr, C++23에서 조건부 noexcept 지원이 추가되었어요.

출처: cppreference

본문

개요

<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의 이전 값을 반환해요.

매개변수 (Parameters)

매개변수 설명
obj 값을 교체할 객체
new_value obj에 할당할 값

타입 요구사항

  • T는 MoveConstructible 요구사항을 충족해야 해요. 또한 U 타입의 객체를 T 타입의 객체로 이동 할당할 수 있어야 해요.

반환값 (Return value)

obj의 이전 값이에요.

예외 (Exceptions)

  • C++23 이전: 없음.
  • C++23부터: noexcept 사양은 다음과 같아요.
    noexcept(std::is_nothrow_move_constructible_v<T> && std::is_nothrow_assignable_v<T&, U>)

가능한 구현 (Possible implementation)

template < class T , class U = T > constexpr // Since C++20 T exchange ( T & obj , U && new_value ) noexcept ( // Since 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 ; }

참고 (Notes)

std::exchange는 이동 생성자와, 특별한 정리가 필요 없는 멤버의 이동 할당 연산자를 구현할 때 사용할 수 있어요.

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); // Move n, while leaving zero in other.n
        // Note: in case of self-move-assignment, n is unchanged
        // Also note: if n is an opaque resource handle that requires
        //            special cleanup, the resource is leaked.
        return *this;
    }
};
Feature-test macro 표준 기능
__cpp_lib_exchange_function 201304L (C++14) std::exchange

예제 (Example)

#include <iostream>
#include <iterator>
#include <utility>
#include <vector>

class stream
{
public:
    using flags_type = int;

public:
    flags_type flags() const { return flags_; }

    // Replaces flags_ by newf, and returns the old value.
    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;

    // Since the second template parameter has a default value, it is possible
    // to use a braced-init-list as second argument. The expression below
    // is equivalent to 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)();

    // The default value of template parameter also makes possible to use a
    // normal function as second argument. The expression below is equivalent to
    // 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, ...

같이 보기 (See also)

함수 설명
swap 두 객체의 값을 교환해요 (함수 템플릿)
atomic_exchange, atomic_exchange_explicit (C++11) 원자 객체의 값을 비원자 인자로 교체하고 이전 값을 반환해요 (함수 템플릿)

더 알아보기 (Learn more)

cppreference