How to check memory allocation failures with new operator?

Well, you call new that throws bad_alloc, so you must catch it:

try
{
    scoped_array<char> buf(new char[MAX_BUF]);
    ...
}
catch(std::bad_alloc&) 
{
    ...
}

or

scoped_array<char> buf(new(nothrow) char[MAX_BUF]);
if(!buf)
{
   //allocation failed
}

What I mean by my answer is that smart pointers propagate exceptions. So if you’re allocating memory with ordinary throwing new, you must catch an exception. If you’re allocating with a nothrow new, then you must check for nullptr. In any case, smart pointers don’t add anything to this logic

Leave a Comment