I have been perusing the web and I haven't found a concrete answer for this but my question is:
Unlikely as it may be these days with the amount of RAM available, what is the best way to handle dynamic memory allocation failures in C++? I know that we can use the built in std::bad_alloc exception but surely wrapping every call to new in a try/catch block can't be healthy?
I have seen the use of new(std::nothrow) but is this the right way to go about it?
I'm interested in this, as well. I was under the impression that a try...catch block in main (encompassing everything) to catch any exceptions that get "elevated" to that level was acceptable.
I think this way is the least obtrusive.
You don't have to use set_new_handler in main, you can put it in any function allocating memory but you only have to use it once. And the function handling the memory error doesn't have to be called handleMemoryDepletion, it's just a function name you pass to set_new_handler.
1 2 3 4 5 6 7 8 9 10 11
#include<new>
void handleMemoryDepletion() {
cout << "Out of memory." << endl; // Or whatever
}
int main() {
set_new_handler(handleMemoryDepletion);
// Code
return 0;
}
Catching the exception in main is usually no better than just letting the program terminate, because if the exception happens during a series of steps (e.g. modifying a database file), part of the process will be left unfinished. Unless you can really handle the exception, that is to correct any potential damage, there's no real point catching it.
I think it depends on what you are doing. If you ran out of memory allocating a small buffer or something then your application is probably in trouble and needs to exit quickly, salvaging what can be salvaged (saving buffers etc...). This could be done with a 'catch all' routine.
Mind you I think you need to guard critical sections of code, like (as Athar says) mid database manipulations. This should be done anyway.
However if your allocating quite a chunk of memory, say to load an image into a graphics program, then you might trap that allocation directly. The application is fine but the user just tried to load something too big. He can be warned and everything continues hunky dory.
Mind you I think you need to guard critical sections of code, like (as Athar says) mid database manipulations. This should be done anyway.More information you can come here http://www.brideswardrobe.com/19-cocktail-dress