#include <iostream>
#include <new>
int main()
{
int n = -1;
try
{
int *p = new(std::nothrow) int[n];
if(!p)
std::cout << "new expression returned nullptr\n";
}
catch(const std::bad_array_new_length& e)
{
std::cout << "new expression threw " << e.what() << std::endl;
}
}
为什么这段代码会抛出异常?它打印new expression threw std::bad_array_new_length
。根据标准,在这种情况下,新表达式应返回 nullptr。
如果 noptr-new-declarator 中的表达式存在,则它被隐式转换为 std::size_t。如果出现以下情况,则该表达式是错误的:
— 表达式是非类类型,并且它在转换为 std::size_t 之前的值小于零;
[...]
如果转换为 std::size_t 后表达式错误:
— 如果表达式是核心常量表达式,则程序格式错误;
— 否则,不调用分配函数;反而
— 如果将被调用的分配函数具有非抛出异常规范 (14.5),则 new-expression 的值是所需结果类型的空指针值;
— 否则,new 表达式通过抛出与 std::bad_array_new_length (17.6.3.2) 类型的处理程序 (14.4) 匹配的类型的异常而终止。
使用 gcc 9.2 编译