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.