Namespaces
Variants
Views
Actions

std::tuple<Types...>::swap

From cppreference.com
< cpp‎ | utility‎ | tuple
 
 
Utilities library
General utilities
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++11)
(C++17)

Elementary string conversions
(C++17)
(C++17)

Stacktrace
 
std::tuple
Member functions
tuple::swap
Non-member functions
(until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
Deduction guides(C++17)
Helper classes
 
Defined in header <tuple>
void swap( tuple& other ) noexcept(/* see below */);
(since C++11)
(until C++20)
constexpr void swap( tuple& other ) noexcept(/* see below */);
(since C++20)

Calls swap (which might be std::swap, or might be found via ADL) for each element in *this and its corresponding element in other.

Contents

[edit] Parameters

other - tuple of values to swap

[edit] Return value

(none)

[edit] Exceptions

noexcept specification:  
noexcept(

    noexcept(swap(std::declval<T0&>>(), std::declval<T0&>())) &&
    noexcept(swap(std::declval<T1&>>(), std::declval<T1&>())) &&
    noexcept(swap(std::declval<T2&>>(), std::declval<T2&>())) &&
    ...

)

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)
noexcept specification:  
noexcept(

    std::is_nothrow_swappable_v<T0> &&
    std::is_nothrow_swappable_v<T1> &&
    std::is_nothrow_swappable_v<T2> &&
    ...

)
(since C++17)

[edit] Example

#include <iostream>
#include <string>
#include <tuple>
 
int main()
{
    std::tuple<int, std::string, float>
                      p1{42, "ABCD", 2.71},
                      p2;
    p2 = std::make_tuple(10, "1234", 3.14);
 
    auto print_p1_p2 = [&](auto rem) {
        std::cout << rem
                  << "p1 = {" << std::get<0>(p1)
                  << ", "     << std::get<1>(p1)
                  << ", "     << std::get<2>(p1) << "}, "
                  << "p2 = {" << std::get<0>(p2)
                  << ", "     << std::get<1>(p2)
                  << ", "     << std::get<2>(p2) << "}\n";
    };
 
    print_p1_p2("Before p1.swap(p2): ");
    p1.swap(p2);
    print_p1_p2("After  p1.swap(p2): ");
    swap(p1, p2);
    print_p1_p2("After swap(p1, p2): ");
}

Output:

Before p1.swap(p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14}
After  p1.swap(p2): p1 = {10, 1234, 3.14}, p2 = {42, ABCD, 2.71}
After swap(p1, p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14}

[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

specializes the std::swap algorithm
(function template) [edit]