“cpp/io/basic fstream/swap2”的版本间的差异

来自cppreference.com
< cpp‎ | io‎ | basic fstream
(r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru)
(Use {{lc}}. Update links. Various fixes.)
第1行: 第1行:
{{page template|cpp/io/basic_fstream/swap2|basic_fstream}}
+
{{page|cpp/io/basic_fstream/swap2|basic_fstream}}
  
 
[[de:cpp/io/basic fstream/swap2]]
 
[[de:cpp/io/basic fstream/swap2]]

2013年7月2日 (二) 09:09的版本

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)
交换两个文件流
(公开成员函数) [编辑]