3 ms·
Why global? Just check if the resource is properly initialized: std::ofstream file("example.txt"); if (!file.is_open()) return; // ofstream will cl
by praptak 10y ago
Why global? Just check if the resource is properly initialized:
std::ofstream file("example.txt");
if (!file.is_open()) return;
// ofstream will close in destructor.
And RAII doesn't even imply that the acquisition must happen via constructor. Edit: Technically it does, but the above pattern would not change if 'file' was a result of calling a free function or whatever.
- lmm 10y ago> Just check if the resource is properly initialized: std::ofstream file("example.txt"); if (!file.is_open()) return; This is exactly not RAII. You acquired the resource and it might not be initialized. And it has the same problem: it's very easy to pass file around when it's not actually valid.
- praptak 10y agoYes, this forces you to explicitly check for errors. I find uninitialized objects' badness comparable to the badness of unhandled exceptions - neither is very hard to debug. But full exception safety is obviously much more than just properly catching exceptions. I mean avoiding subtle traps like the ones here: https://herbsutter.com/gotw/_102/ https://herbsutter.com/gotw/_102/
- realharo 10y ago>I find uninitialized objects' badness comparable to the badness of unhandled exceptions - neither is very hard to debug. Unless you have a bunch of code that just passes the object around without looking into it (so it won't fail there), and then when the crash finally happens, you have no idea where the invalid object came from. This is really just another form of the billion dollar mistake, except you have invalid objects instead of null pointers (or in the worst case, you have both). With an unhandled exception, you always have the context of where and why it happened (assuming you know the reason behind throwing it).
- Aeolos 10y agoThis code suffers from a race condition: the file might be deleted/moved/renamed at any point, even if the file.is_open() check succeeds. Code that does not consider this possibility is technically fragile under a wide set of pretty common conditions.
- prodigal_erik 10y agoWindows doesn't allow deleting an open file. Unix allows the deleted file to be used (even for IPC) and doesn't GC it until it's closed. Breaking an open file's user would be bad design requiring some kind of complicated notification system to be at all usable.