I'm working on a performance-critical dynamically-linked library (DLL) that should also have a relatively small binary size. Since it doesn't explicitly throw any exceptions, I'd like to disable exception support altogether. However, there's one exception (pun unintended): when running out of memory (OOM), I have to report an error code to the application so it has a chance to handle things gracefully. The code base is too large to check every allocation individually and propagate the error, and contains external code that I shouldn't touch. So I'd like to catch OOM exceptions in my DLL's exported functions.
A quick test shows that when disabling C++ exceptions in Visual C++ 2010 (i.e. no /EHa, /EHsc or /EHs flags), it still jumps to a catch(std::bad_alloc&) block when allocating too much memory.
So it seems to work as desired. However, I get the following level 1 warning: "C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc". MSDN says that "an object with automatic storage in the frame, between the function doing the throw and the function catching the throw, will not be destroyed".
Exactly what would I lose here? It's fine to leave things in an undefined state, as long as anything that was created through the library can be deleted, and the application can start over again (if it so chooses). Is there a big risk of leaking memory that cannot be recovered?
Do DLLs use a separate memory pool? And if so, can I purge it without requiring the application to unload the DLL? I can easily make my library ignore any further (exported) function calls until the application performs a reinitialization.
Thanks for your advice.
bad_alloc
happens, then you are fine with that, I suppose [as long a you don't have strange resources that don't get cleaned up with program exit - but most should]. If you are wanting to "continue" afterbad_alloc
, then the code will need to track objects and destroy all objects created in stack frames between thethrow
andcatch
. You can experiement by writing some small code that has printouts in destructors. – Mats Petersson