命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | utility‎ | tuple
 
 
 
 
定义于头文件 <tuple>
void swap( tuple& other ) noexcept(/* 见下文 */);
(1) (C++11 起)
(C++20 起为 constexpr)
constexpr void swap( const tuple& other ) noexcept(/* 见下文 */) const;
(2) (C++23 起)

*this 中的每个元素及其在 other 中对应的元素调用 swap (可能是 std::swap,也可能通过 ADL 找到)。

如果任何选定的 swap 函数调用格式不正确,或者没有交换两个 tuple 的相应元素,则行为未定义。

(直至 C++23)

如果任何选定的 swap 函数调用没有交换两个 tuple 的相应元素,则行为未定义。

1) 如果 (std::is_swappable_v<Types> && ...) 不为 true,则程序格式错误。
2) 如果 (std::is_swappable_v<const Types> && ...) 不为 true,则程序格式错误。
(C++23 起)

目录

[编辑] 参数

其他 - 要交换的 tuple 值

[编辑] 返回值

(无)

[编辑] 异常

noexcept 规范:  
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&>())) &&
    ...

)

在上述表达式中,标识符 swap 的查找方式与 C++17 std::is_nothrow_swappable 特性使用的查找方式相同。

(C++17 前)
1)
noexcept 规范:  
noexcept((std::is_nothrow_swappable_v<Types> && ...))
2)
noexcept 规范:  
noexcept((std::is_nothrow_swappable_v<const Types> && ...))
(C++17 起)

[编辑] 示例

#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): ");
}

输出

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}

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 2456 C++11 noexcept 规范格式错误 已修复

[编辑] 另请参阅

特化 std::swap 算法
(函数模板) [编辑]
(C++11)
交换内容
(std::pair<T1,T2> 的公共成员函数) [编辑]