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()?
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);
- Effects: Calls
this->close()
then move assigns fromrhs
. After the move assignment*this
has the observable state it would have had if it had been move constructed fromrhs
.- Returns:
*this
.
basic_fstream& operator=(basic_fstream&& rhs);
- Effects: Move assigns the base and members of
*this
from the base and corresponding members ofrhs
.- Returns:
*this
.
(This is the wording from draft n4527, unchanged since at least n3485)