When using new and a bad_alloc exception is thrown. Do you still need to call delete on the ptr before carrying on or can you be confident that no memory has been allocated?
How about if you use the nothrow version? can you again be confident that no memory has been allocated if a nullptr is returned?
When an exception is thrown, you don't "carry on" - execution jumps to the catch handler.
In an expression like:
p = new int;
the sub-expression new int
is evaluated first. If that throws an exception then execution does not reach the assignment. p
retains the previous value it had (if any).
In the case p = new(std::nothrow) int;
then if allocation fails, p
will become a null pointer. It has no effect to invoke delete
on a null pointer.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With