#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 throw std::bad_array_new_length
。
根据标准,在这种情况下,新表达式应返回 nullptr。
If the expression in a noptr-new-declarator is present, it is implicitly converted to 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;
[...]
If the expression is erroneous after converting to 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;
— 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).
使用 gcc 9.2 编译
最佳答案
我怀疑这是 libstdc++ 中的错误;使用 clang 和 libc++ 运行此代码打印“新表达式返回 nullptr”
关于c++ - new(std::nothrow) int[n] 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59414654/