3 ms·
> The big problem with RAII and destructors is that you have no way of returning an error. That's actually a feature. Destructors are for cleanup. If code is s
by ExpiredLink 15y ago
> The big problem with RAII and destructors is that you have no way of returning an error.
That's actually a feature. Destructors are for cleanup. If code is supposed to report an error (by throwing an exception) it should not be put into a destructor.
- cageface 15y agoSo if I have an RAII object that supposed to close or delete a file and that fails for some reason, then what?
- ExpiredLink 15y agoIt depends. - If the file has been opened for reading only you can put fclose into the destructor and safely ignore the return value. - If the file has been opened for writing you need to call fclose() before the destructor to be able to react accordingly. Throwing an exception in the destructor would not be helpful in this case anyway because your scope is gone. BTW, writing a file safely is much harder than what many internet sources and textbooks make it appear.
- cageface 15y agoBut similar constructions in other languages (Python's with- statement, various Lisp versions, using in C#) can handle this cleanly. C++ doesn't give you "finally" and since you can't do non-trivial cleanup in destructors RAII is really a lot less useful than it seems at first blush.
- ExpiredLink 15y agoIn C++ you can write the cleanup code once in the destructor, "similar constructions in other languages" must be written every time you use it. You can and should do "non-trivial cleanup in destructors", e.g. DB rollback, but you should do only cleanup in destructors.