New (std::nothrow) vs. New within a try/catch block

Anne Quinn picture Anne Quinn · Sep 2, 2011 · Viewed 18.9k times · Source

I did some research after learning new, unlike malloc() which I am used to, does not return NULL for failed allocations, and found there are two distinct ways of checking whether new had succeeded or not. Those two ways are:

try
{
    ptr = new int[1024];
}
catch(std::bad_alloc& exc)
{
    assert();
};

and

ptr = new (std::nothrow) int[1024];
if(ptr == NULL) 
    assert();

I believe the two ways accomplish the same goal, (correct me if I am wrong of course!), so my question is this:

which is the better option for checking if new succeeded, based entirely on readability, maintainability, and performance, while disregarding de-facto c++ programming convention.

Answer

Nicol Bolas picture Nicol Bolas · Sep 2, 2011

Consider what you are doing. You're allocating memory. And if for some reason memory allocation cannot work, you assert. Which is more or less exactly what will happen if you just let the std::bad_alloc propagate back to main. In a release build, where assert is a no-op, your program will crash when it tries to access the memory. So it's the same as letting the exception bubble up: halting the app.

So ask yourself a question: Do you really need to care what happens if you run out of memory? If all you're doing is asserting, then the exception method is better, because it doesn't clutter your code with random asserts. You just let the exception fall back to main.

If you do in fact have a special codepath in the event that you cannot allocate memory (that is, you can actually continue to function), exceptions may or may not be a way to go, depending on what the codepath is. If the codepath is just a switch set by having a pointer be null, then the nothrow version will be simpler. If instead, you need to do something rather different (pull from a static buffer, or delete some stuff, or whatever), then catching std::bad_alloc is quite good.