Based on the C ++ specification, it will always call std :: bad_alloc when you use just the new without parameters, but of course there may be some inappropriate compilers.
I would not code to be compatible with compilers that are not compatible with C ++. VC6 is one of them in this regard.
This is good practice, although always pointing your pointer to NULL after they are removed. Therefore, because of this, NULL checking is still necessary.
As the saying goes, here are a couple of options for cleaning up your code:
Option 1: Install Your Own New Handler
A safe way to clear code would be: set_new_handler .
Then you can check for NULL in your handler and throw std :: bad_alloc there if NULL is returned.
If you prefer exceptions, then this is your best bet. If you like returning NULL better, you can also do this by catching inside your new handler.
Option 2: using an overloaded new
The standard C ++ header file defines a struct nothrow that is empty. You can use the object of this structure inside new to get your overloaded version, which always returns NULL.
void* operator new (size_t size, const std::nothrow_t &); void* operator new[] (void *v, const std::nothrow_t &nt);
So in your code:
char *p = new(std::nothrow) char[1024];
Here is a good confirmation for further reading.
Brian R. Bondy Feb 15 '09 at 7:13 2009-02-15 07:13
source share