Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On new's bad allocation error, does delete still need to be called?

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?

like image 425
uhsl_m Avatar asked Sep 02 '25 15:09

uhsl_m


2 Answers

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.

like image 105
M.M Avatar answered Sep 05 '25 06:09

M.M


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.)

like image 24
Kerrek SB Avatar answered Sep 05 '25 05:09

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!