[英]new(std::nothrow) int[n] throws an exception
#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;
}
}
Why does this code throw an exception?为什么这段代码会抛出异常? It prints
new expression threw std::bad_array_new_length
.它打印
new expression threw std::bad_array_new_length
。 According to the standard the new expression should return nullptr in this case.根据标准,在这种情况下,新表达式应返回 nullptr。
If the expression in a noptr-new-declarator is present, it is implicitly converted to std::size_t.
如果 noptr-new-declarator 中的表达式存在,则它被隐式转换为 std::size_t。 The expression is erroneous if:
如果出现以下情况,则表达式是错误的:
— the expression is of non-class type and its value before converting to std::size_t is less than zero;
— 表达式为非类类型且其值在转换为 std::size_t 之前小于零;
[...]
[...]
If the expression is erroneous after converting to std::size_t:
如果转换为 std::size_t 后表达式错误:
— if the expression is a core constant expression, the program is ill-formed;
— 如果表达式是核心常量表达式,则程序格式错误;
— otherwise, an allocation function is not called;
— 否则,不调用分配函数; instead
反而
— if the allocation function that would have been called has a non-throwing exception specification (14.5), the value of the new-expression is the null pointer value of the required result type;
— 如果将被调用的分配函数具有非抛出异常规范 (14.5),则 new 表达式的值是所需结果类型的空指针值;
— otherwise, the new-expression terminates by throwing an exception of a type that would match a handler (14.4) of type std::bad_array_new_length (17.6.3.2).
— 否则,new 表达式通过抛出与 std::bad_array_new_length (17.6.3.2) 类型的处理程序 (14.4) 匹配的类型的异常而终止。
Compiled with gcc 9.2用 gcc 9.2 编译
I suspect that this is a bug in libstdc++;我怀疑这是 libstdc++ 中的一个错误; running this code using clang and libc++ prints "new expression returned nullptr"
使用 clang 和 libc++ 运行此代码打印“新表达式返回 nullptr”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.