C++ 编译器如何处理 new 运算符期间的 malloc 失败?

How do C++ compilers handle malloc failures during new operator?

C++ 编译器将 new Obj 实现为 malloc(sizeof(Obj)) 的包装器。但是 malloc 可能会失败! C++ 编译器插入什么代码来处理失败,它有什么作用?

C++ 标准对行为的描述:

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

在非抛出情况下,不需要处理,因为返回 null 正是 malloc 表示失败的方式。

在抛出的情况下,包装 malloc 的语言实现必须检查分配是否成功,如果不成功则抛出。