c++c++11streamcopy-constructorcopy-and-swap

When to use std::swap for stream types?


Trying to give an answer to this question text-file-handling-in-c giving references to cplusplus.com. I came across to the std::swap-function for stream-types like fstream.

So my question is: What exactly is the purpose of a swap functionality e.g. for a 'fstream' respectively in which situation do I have to use it?

Referencing to to the Q&A C++ std::ifstream in constructor problem I know that stream types are non-copyable. Referencing to the Q&A What is the copy-and-swap idiom? the swap-functionality is e.g. given to implement a copy-constructor,... . So are stream-types having the swapping-feature now copyable with the swap-feature -> If so, how do the language-developers achieved it?


Solution

  • Well, unsurprisingly, you use std::swap for streams when you want to swap around streams. You can for example use this to std::remove_if all "bad" streams from a vector of streams (ok, this is probably not the best example. I can't come up with a better one of the top of my head).

    As for how this works: Since C++11, the standard streams are move constructable and move assignable. So while you still cannot copy them, you can swap them with a generic swap function like:

    template <class T>
    void swap (T &a, T &b) {
        auto temp = std::move(a);
        a = std::move(b);
        b = std::move(temp);
    }
    

    Now our streams are swapped without ever having to copy them.

    By the way, the streams being swapable does not make them copyable. When you look the example copy assignment operator

    MyClass& operator=(const MyClass& other)
    {
        MyClass tmp(other);
        swap(tmp);
        return *this;
    }
    

    from the question you linked, you will notice this line:

    MyClass tmp(other);
    

    which requires a copy constructor, something the streams do not have.