命名空间
变体
操作

std::swap(std::basic_ofstream)

来自 cppreference.cn
< cpp‎ | io‎ | basic ofstream
template< class CharT, class Traits >
void swap( basic_ofstream<CharT, Traits>& lhs, basic_ofstream<CharT, Traits>& rhs );

为 std::basic_ofstream 特化 std::swap 算法。交换 lhs 的状态与 rhs 的状态。实际调用 lhs.swap(rhs) 。

内容

[edit] 参数

lhs, rhs - 要交换状态的流

[edit] 返回值

(无)

[edit] 异常

可能抛出实现定义的异常。

[edit] 示例

#include <fstream>
#include <iostream>
#include <string>
 
bool create_stream(std::ofstream& fs)
{
    try
    {
        std::string some_name = "/tmp/test_file.txt";
        std::ios_base::openmode some_flags = fs.trunc; // | other flags
 
        if (std::ofstream ts{some_name, some_flags}; ts.is_open())
        {
            std::swap(ts, fs); // stream objects are not copyable => swap
            return true;
        }
    }
    catch (...)
    {
        std::cout << "Exception!\n";
    }
    return false;
}
 
int main()
{
    if (std::ofstream fs; create_stream(fs))
    {
        // use fs stream
    }
}

[edit] 参见

(C++11)
交换两个文件流
(公开成员函数) [编辑]