Re: bad_alloc in new
* George2:
Hello everyone,
I usually check whether there is bad_alloc thrown to identify whether
the allocation is success or not.
My question is,
Is there a way to disable bad_alloc and just to check the returned
pointer NULL or not to identify allocation success or not -- which
from function point of view, is as correct as the way to catch
bad_alloc?
Yes, you can do
#include <new>
int main()
{
int* p = new(nothrow) int(42);
if( p == 0 ) {}
}
(I can't remember whether nothrow is required to be in the global
namespace, or possibly is just in namespace std: modify as necessary).
However, except for embedded platform programming (and even there)
that's generally not a good way to handle memory exhaustion.
In general, when memory is exhausted the only practical option is to
bail out by aborting the program, possibly after logging.
And to do that, use set_new_handler.
Windows platform/Visual Studio is ok. I always see code
does not check bad_alloc and just check the return pointer.
Either that's pre-standard code or code written by someone who doesn't
know C++: with standard C++ it's meaningless.
(My solution is to select Enable C++ Exception to No in Code
Generation option in Visual Studio, not sure whether it is the most
correct way.)
Since e.g. the standard library is based on having C++ exception
support, that's generally not a good idea. Consider a constructor failing.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?