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()?
When the fstream/ifstream/ofstream object is out of scope, the file will be closed automatically. However, you can explicitly call the close() function to close it and release the resource if the fstream object will not be out of scope for a while.
fstream is a proper RAII object, it does close automatically at the end of the scope, and there is absolutely no need whatsoever to call close manually when closing at the end of the scope is sufficient. In particular, it's not a “best practice” and it's not necessary to flush the output.
NOTE: close() is typically called through the destructor of std::basic_filebuf (which, in turn, is typically called by the destructor of std::basic_fstream . First of all, we can see that it doesn't actually call flush() directly as you expected.
There is no harm in closing it manually, but it's not the C++ way, it's programming in C with classes. If you want to close the file before the end of a function you can always use a nested scope. In the standard (27.8.
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)
Since actual file-related machinery is 'hidden' inside corresponding buffers (streams really mostly provide formatting IO), you should be looking at std::basic_filebuf
documentation:
First calls close() to close the associated file, then moves the contents of rhs into *this: the put and get buffers, the associated file, the locale, the openmode, the is_open flag, and any other state. After the move, rhs is not associated with a file and rhs.is_open() == false.
Copy from http://en.cppreference.com/w/cpp/io/basic_filebuf/operator%3D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With