Namespaces
Variants
Views
Actions

std::pair<T1,T2>::swap

From cppreference.com
< cpp‎ | utility‎ | pair
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)

(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++23)
(C++11)
(C++17)

Elementary string conversions
(C++17)
(C++17)
 
std::pair
Member functions
pair::swap
(C++11)
Non-member functions
(until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
(C++11)
(C++11)
Deduction guides(C++17)
Helper classes
(C++11)
 
(1)
void swap( pair& other ) noexcept(/* see below */);
(since C++11)
(until C++20)
constexpr void swap( pair& other ) noexcept(/* see below */);
(since C++20)
constexpr void swap( const pair& other ) noexcept(/* see below */);
(2) (since C++23)

Swaps first with other.first and second with other.second, as if by using std::swap; swap(first, other.first); swap(second, other.second);.

If either selected swap function call is ill-formed or does not swap the value of the member, the behavior is undefined.

(until C++23)
1) The program is ill-formed if either std::is_swappable_v<T1> or std::is_swappable_v<T2> is not true.
2) The program is ill-formed if either std::is_swappable_v<const T1> or std::is_swappable_v<const T2> is not true.

If either selected swap function call does not swap the value of the member, the behavior is undefined.

(since C++23)

Contents

[edit] Parameters

other - pair of values to swap

[edit] Return value

(none)

[edit] Exceptions

noexcept specification:  
noexcept(

     noexcept(swap(first, other.first)) &&
     noexcept(swap(second, other.second))

)

In the expression above, the identifier swap is looked up in the same manner as the one used by the C++17 std::is_nothrow_swappable trait.

(until C++17)
1)
noexcept specification:  
noexcept(

     std::is_nothrow_swappable_v<first_type> &&
     std::is_nothrow_swappable_v<second_type>

)
2)
noexcept specification:  
noexcept(

     std::is_nothrow_swappable_v<const first_type> &&
     std::is_nothrow_swappable_v<const second_type>

)
(since C++17)

[edit] Example

#include <iostream>
#include <utility>
#include <string>
int main()
{
    std::pair<int, std::string> p1, p2;
    p1 = std::make_pair(10, "test");
    p2.swap(p1);
    std::cout << "(" << p2.first << ", " << p2.second << ")\n";
}

Output:

(10, test)

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 2456 C++11 the noexcept specification is ill-formed made to work

[edit] See also

swaps the values of two objects
(function template) [edit]
(C++11)
swaps the contents of two tuples
(public member function of std::tuple<Types...>) [edit]