c++ - new(std::nothrow) int[n] 抛出异常

标签 c++ gcc c++17 new-operator nothrow

#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/

相关文章:

gcc - calloc 崩溃

c++ - 使用 BYTE 类型的变量是否可移植?

c++ - std::string_view 编译时散列

c++ - 将整数常量映射到类型

c++ - 如何在 Windows 8 中获取窗口标题栏(事件和非事件)颜色?

c++ - Elem 没有命名类型?

c++ - boost::interprocess 共享内存删除对象而不破坏

c++ - OpenGL 应用程序有时会崩溃

c - 采用 2 个位置参数的 C 语言示例应用程序

c++ - 递归嵌套初始值设定项列表采用变体