Search code examples
c++filestreammove

Does move assign an std::fstream close the original stream


Since c++11, we can move assign one std::fstream object to another, but I'm unable to find documentation that states, what happens if the fstream object is already associated with a file (is_open()==true).

So my question is whether in the following code, File1.txt will properly be closed or if I have to close it manually. And if I have to do it manually, what happens if I don't?

std::fstream file("File1.txt");   
file = std::fstream("File2.txt"); //will this implicitly call file.close()?             

Solution

  • Move-assignment of an fstream object will result in move-assignment of its associated filebuf. The documentation for that makes it pretty clear that the old file is closed first (as-if file.rdbuf()->close() not file.close()):

    basic_filebuf& operator=(basic_filebuf&& rhs);

    1. Effects: Calls this->close() then move assigns from rhs. After the move assignment *this has the observable state it would have had if it had been move constructed from rhs.
    2. Returns: *this.

    basic_fstream& operator=(basic_fstream&& rhs);

    1. Effects: Move assigns the base and members of *this from the base and corresponding members of rhs.
    2. Returns: *this.

    (This is the wording from draft n4527, unchanged since at least n3485)