The nothrow version of new
does indeed report errors by returning a null pointer, in which case no memory has been allocated and no object has been constructed:
T * p = new (std::nothrow) T(a, b, c);
if (p)
{
// stuff
}
delete p; // OK, works on null pointers, too.
Or maybe:
if (T * p = new (std::nothrow) T(a, b, c))
{
// stuff
delete p;
}
else
{
// allocation failure
}
Or even better:
if (std::unique_ptr<T> p(new (std::nothrow) T(a, b, c)))
{
// stuff
}
The last version automatically deletes the dynamic object on any exit from the if
block, which is a typical example of C++'s way of handling multiple exits and thus localizing complexity.
(Maybe there should be a make_unique_or_null
function template to encapsulate this last bit.)