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

来自cppreference.com
< cpp‎ | utility‎ | pair
 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
 
(1)
void swap( pair& other ) noexcept(/* 见下文 */);
(C++11 起)
(C++20 前)
constexpr void swap( pair& other ) noexcept(/* 见下文 */);
(C++20 起)
constexpr void swap( const pair& other ) noexcept(/* 见下文 */);
(2) (C++23 起)

交换 firstother.firstsecondother.second,如同用 using std::swap; swap(first, other.first); swap(second, other.second);

若任一选择的 swap 函数调用非良构或不交换成员的值,则行为未定义。

(C++23 前)
1)std::is_swappable_v<T1>std::is_swappable_v<T2>true 则程序非良构。
2)std::is_swappable_v<const T1>std::is_swappable_v<const T2>true 则程序非良构。

若任一选择的 swap 函数调用不交换成员的值,则行为未定义。

(C++23 起)

参数

other - 要交换值的对偶

返回值

(无)

异常

noexcept 说明:  
noexcept(

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

)

在上述表达式中,按照与 C++17 std::is_nothrow_swappable 特征所用的相同方式查找标识符 swap

(C++17 前)
1)
noexcept 说明:  
noexcept(

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

)
2)
noexcept 说明:  
noexcept(

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

)
(C++17 起)

示例

#include <iostream>
#include <utility>
#include <string>
int main()
{
    std::pair<int, std::string> p1(10, "test"), p2;
    p2.swap(p1);
    std::cout << "(" << p2.first << ", " << p2.second << ")\n";
 
#if __cpp_lib_ranges_zip >= 202110L
    // 使用 C++23 const 限定的 swap 重载
    // (swap 不再传播对偶的常量性)
    int i1 = 10, i2{};
    std::string s1("test"), s2;
    const std::pair<int&, std::string&> r1(i1, s1), r2(i2, s2);
    r2.swap(r1);
    std::cout << "(" << i2 << ", " << s2 << ")\n";
#endif
}

可能的输出:

(10, test)
(10, test)

缺陷报告

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

缺陷报告 应用于 出版时的行为 正确行为
LWG 2456 C++11 noexcept 说明曾为非良构 使之有效

参阅

交换两个对象的值
(函数模板)
交换两个 tuple 的内容
(std::tuple<Types...> 的公开成员函数)