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

std::exchange cppreference.com
cppreference.com

std::exchange

cppreference.com
<tbody> </tbody> <tbody class="t-dcl-rev "> </tbody><tbody> </tbody>
template< class T, class U = T > T exchange( T& obj, U&& new_value );
( C++14)
( C++20)
template< class T, class U = T > constexpr T exchange( T& obj, U&& new_value );
( C++20)
( C++23)
template< class T, class U = T > constexpr T exchange( T& obj, U&& new_value ) noexcept(/* */);
( C++23)

obj new_value obj.

obj ,
new_value obj
-
T MoveConstructible. , - U T

obj

()

( C++23)
noexcept:  
noexcept( std::is_nothrow_move_constructible_v<T> && std::is_nothrow_assignable_v<T&, U> )
( 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 :

struct S
{
    int n;

    S(S&& other) noexcept : n{std::exchange(other.n, 0)}
    {}
  
    S& operator=(S&& other) noexcept
    {
        if (this != &other)
            n = std::exchange(other.n, 0); //  n,    other.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\n : ";
    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()

 : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...


( ) []

( ) []

Web Proxy Viewer  |  New URL  |  Original Page