3 ms·
A problem is if you use RAII for other resources than memory, for example files. You want to put the close function in the destructor then, but close can throw
by andi999 7y ago
A problem is if you use RAII for other resources than memory, for example files. You want to put the close function in the destructor then, but close can throw an exception. http://www.cplusplus.com/reference/fstream/ofstream/close/ http://www.cplusplus.com/reference/fstream/ofstream/close/
(Of course the solution is easy, you wrap close in a try catch block, but as alwaya all the solutions are easy in c++ but this is one of the surprising corners, which might be done more often wrong then not)
- laurowyn 7y agoInteresting corner case that I can't say I've ever seen before. fstream is a bit of a mess. Even the documentation for close is a bit contradictory. Its exception safety states that an exception is caught and rethrown after closing the file if one is thrown by an internal operation. That to me sounds like the actual resource being managed will be closed (assuming the fd is valid), but any data may not be flushed out of the write buffer. sounds to me like iostream needs some serious attention in future specs, but that's unlikely to happen unfortunately. Creating new toys > fixing old ones.
- gpderetta 7y agoFstream is hardly a paragon of good design. Then again there is no reason to call close in the destructor as fstream destructor itself will call close. If you care about reliability and want to make sure your stream is flushed, you probably want an explicit commit interface and reserve the destructor for rollback (which necessarily shouldn't possibly fail).
- deleted 7y ago[deleted]