Reputation: 9206
C++ compilers implement new Obj
as a wrapper to malloc(sizeof(Obj))
. But malloc can fail! What code do C++ compilers insert to handle the failures, and what does it do?
Upvotes: 0
Views: 63
Reputation: 238351
C++ standard says about the behaviour:
[basic.stc.dynamic.allocation]
An allocation function that has a non-throwing exception specification ([except.spec]) indicates failure by returning a null pointer value. Any other allocation function never returns a null pointer value and indicates failure only by throwing an exception ([except.throw]) of a type that would match a handler ([except.handle]) of type std::bad_alloc ([bad.alloc]).
In the non-throwing case, there is no handling needed because returning null is exactly how malloc
signifies failure.
In the throwing case, a language implementation that wraps malloc
has to check whether the allocation was successful, and throw if it wasn't.
Upvotes: 2