名稱空間
變體
操作

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

來自 cppreference.com
< 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> 的公共成員函式) [編輯]