Background
Before the introduction of unique_ptr (or boost's scoped pointers) there was this kind of boiler plate pointer memory management everywhere.
int* a = new int(5);
// do stuff
delete a;
a = nullptr
Now we can just do
std::unique_ptr<int> a = std::make_unique<int>(5);
That's it! When a falls out of scope it will take care of all of the cleanup. Not only is it a convenience, it actually helps prevent memory leaks in the case of early returns or thrown exceptions.
Question
When writing to a file stream I notice the same boiler plate code
std::ofstream ofs;
ofs.open("out.txt");
// writing stuff
ofs.close();
Is there a similar mechanism to handle file opening and closing via RAII? So when the stream (or some kind of wrapper) falls out of scope, it will automatically fall out of scope and release the file handle? Otherwise we may have the same issue we had with pointers, where if you return early the file may not be closed.
ofstream itself is scope-bound, with constructors that can open a file and a destructor that closes it. So you can just write
{
std::ofstream ofs("out.txt");
// writing stuff
}
with the same behaviour as your code, plus RAII goodness.
According to http://en.cppreference.com/w/cpp/io/basic_fstream the file will get closed when destructor is called, so file streams should be RAII already.
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