Namespaces
Variants

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

From cppreference.net
Utilities library
(1)
void swap ( pair & other ) noexcept ( /* see below */ ) ;
(C++11 起)
(C++20 前)
constexpr void swap ( pair & other ) noexcept ( /* see below */ ) ;
(C++20 起)
constexpr void swap ( const pair & other ) const noexcept ( /* see below */ ) ;
(2) (C++23 起)

交换 first other.first ,并交换 second other.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 起)

目录

参数

其他 - 需要交换的值对

返回值

(无)

异常

noexcept 规范:
noexcept (

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

)

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

(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 常量限定的 swap 重载
    // (swap 不再传播 pair 的常量性)
    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...> 的公开成员函数)