void * nullptr 时运算符重载 new 使程序崩溃

Operator overloaded new when void * nullptr makes the program to crash

我有一个代码可以通过 GMOCK 进行测试,但遇到了一个特殊问题。

有一个重载新运算符的class,重载方法有一个逻辑return (void*) nullptr 在创建更多时说2 个对象。

现在在主代码中我们有一个 for 循环进行 5 次迭代 - 我期望从第 3 次迭代开始 new 运算符将 return nullptr 但程序实际上崩溃了。

从您的操作员处返回 nullptr 会导致未定义的行为。
来自 3.7.4.1 分配函数:

(2) The allocation function attempts to allocate the requested amount of storage. If it is successful, it shall return the address of the start of a block of storage whose length in bytes shall be at least as large as the requested size.

(3) An allocation function that fails to allocate storage can invoke the currently installed new-handler function (18.6.2.3), if any. [ Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the std::get_new_handler function (18.6.2.4). — end note ] If an allocation function declared with a non-throwing exception-specification (15.4) fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall indicate failure only by throwing an exception of a type that would match a handler (15.3) of type std::bad_alloc (18.6.2.1).

当你重载抛出 new 运算符时,你不应该 return nullptr