4 ms·
It 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 o
by ExpiredLink 15y ago
It 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.