std::swap(std::basic_fstream)

出自cppreference.com
< cpp‎ | io‎ | basic fstream
在2017年9月23日 (六) 21:46由Fruderica對話 | 貢獻所做的修訂版本

(差異) ←上一修訂 | 最新修訂 (差異) | 下一修訂→ (差異)
template< class CharT, class Traits >
void swap( basic_fstream<CharT, Traits>& lhs, basic_fstream<CharT, Traits>& rhs );

std::basic_fstream 特化 std::swap 算法。交換 lhsrhs 的狀態。相當於調用 lhs.swap(rhs)

目錄

[編輯] 參數

lhs, rhs - 要交換狀態的流

[編輯] 返回值

(無)

[編輯] 異常

可能會拋出由實現定義的異常。

[編輯] 示例

#include <fstream>
#include <iostream>
#include <string>
 
bool create_stream(std::fstream& fs)
{
    try
    {
        std::string some_name = "/tmp/test_file.txt";
        std::ios_base::openmode some_flags = fs.trunc; // | 其他标志
 
        if (std::fstream ts{some_name, some_flags}; ts.is_open())
        {
            std::swap(ts, fs); // 流对象不可复制 => swap
            return true;
        }
    }
    catch (...)
    {
        std::cout << "Exception!\n";
    }
    return false;
}
 
int main()
{
    if (std::fstream fs; create_stream(fs))
    {
        // 使用流 fs
    }
}

[編輯] 參閱

(C++11)
交換兩個文件流
(公開成員函數) [編輯]