If I have a function I call when there is an error in my app, and I call ExitProcess
in that function to exit. Do I need to find a way to have it call things like W开发者_开发知识库SACleanup()
and ReleaseMutex
and RemoveFontMemResourceEx
, and free other manually allocated variables?
I believe the system does this automatically when my application exits, but is there a reason i'd want to call these cleanup functions anyways? And if I don't, do I need to even call them right before my application exits?
The title is "C++ error cleanup question", and there is a [c++] tag on it, so... Why aren't your resources (memory, network connections, mutexes, critical sections, etc.) handled by RAII?
If you have an error, then throw an exception, handle it higher on the stack if you can handle it, and let it crash the app if you can't (or catch it in the main, and exit the main gracefully with an error code).
Upon stack unwinding, all your RAII-protected resources will be cleaned away (so you won't have any resource leak).
The advantage of the solution is:
- You don't have to deal with resources yourself, as RAII does it automatically.
- If one day you believe you can handle an error, just catch the exception at the point you can handle it, and recover.
Most (all?) modern operating systems release most resources when a process exits, so most of the time it's safe to just exit. But there are reasons to release them explicitly.
First, if you use resource leakage detection tools (like valgrind for memory leaks for example), it's gonna give you false positives.
Second, if your code gets refactored in the future, you may forget about some resources and cause leakage.
So I think it's always a good idea to release resources as soon as you're done with them.
The atexit
function might be useful - http://www.cplusplus.com/reference/clibrary/cstdlib/atexit/
精彩评论