问题
I'm trying to design a class that needs to dynamically allocate some memory..
I had planned to allocate the memory it needs during construction, but how do I handle failed memory allocations? Should I throw an exception? I read somewhere that exceptions should only be used for "exceptional" cases, and running out of memory doesn't seem like an exceptional case to me..
Should I allocate memory in a separate initialization routine instead and check for failures and then destroy the class instance gracefully?
Or should I use exceptions instead? The class won't have anything useful to do if these memory allocations should fail..
EDIT: The consensus seems to be that running out of memory IS an exceptional case.
Will see how to go about this.. Thanks.. :)
回答1:
Assuming you are using new to allocate memory, and are not overriding the new
operator, it will automatically throw the std::bad_alloc
exception if it fails to allocate memory properly.
I read somewhere that exceptions should only be used for "exceptional" cases, and running out of memory doesn't seem like an exceptional case to me..
Running out of memory seems like a pretty exceptional case to me :)
It is very difficult to handle this sort of situation. You may want to return a meaningful error to the user of your application, but if it's a problem caused by lack of memory, you may not even be able to afford the memory to allocate the error message. It's a bit of a catch-22 situation really.
There is a defensive programming technique (sometimes called a memory parachute or rainy day fund) where you allocate a chunk of memory when your application starts. When you then handle the bad_alloc
exception, you free this memory up, and use the available memory to close down the application gracefully, including displaying a meaningful error to the user. This is much better than crashing :)
回答2:
I would argue that running out of memory (particularly heap memory) is an exceptional case, and if your class - and further, your application - cannot continue, I think exception throwing/handling is a very appropriate and graceful approach.
回答3:
The usual behaviour in C++ when you are out of memory is to throw an exception. The built-in new
operator does this by default.
来源:https://stackoverflow.com/questions/584599/when-is-it-appropriate-to-use-c-exceptions