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.. :)
-
The usual behaviour in C++ when you are out of memory is to throw an exception. The built-in
newoperator does this by default. -
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.
-
Assuming you are using new to allocate memory, and are not overriding the
newoperator, it will automatically throw thestd::bad_allocexception 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_allocexception, 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 :)krebstar : YES! This is the approach I want to do.. thanks :)
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.