命名空间
变体
操作

std::bad_array_new_length

来自 cppreference.cn
< cpp‎ | 内存‎ | new
 
 
 
内存管理库
(仅作说明*)
未初始化内存算法
(C++17)
(C++17)
(C++17)
受约束的未初始化
内存算法
C 库

分配器
内存资源
垃圾回收支持
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化存储
(直到 C++20*)
(直到 C++20*)
显式生命周期管理
 
 
定义于头文件 <new>
class bad_array_new_length;
(C++11 起)

std::bad_array_new_length 是由 new 表达式 抛出的异常类型,用于报告以下情况的无效数组长度:

  1. 数组长度为负数,
  2. 新数组的总大小将超过实现定义的预设最大值,
  3. 初始化子句的数量超过要初始化的元素数量。

只有第一个数组维度可能产生此异常;除了第一个维度之外的维度是常量表达式,并在编译时进行检查。

cpp/error/exceptioncpp/memory/new/bad allocstd-bad array new length-inheritance.svg

继承图

目录

[编辑] 成员函数

(构造函数)
构造一个新的 bad_array_new_length 对象
(公开成员函数)
operator=
替换 bad_array_new_length 对象
(公开成员函数)
what
返回解释字符串
(公开成员函数)

std::bad_array_new_length::bad_array_new_length

bad_array_new_length() noexcept;
(1) (C++11 起)
bad_array_new_length( const bad_array_new_length& other ) noexcept;
(2) (C++11 起)

构造一个新的 bad_array_new_length 对象,其包含一个实现定义的以 null 结尾的字节字符串,该字符串可通过 what() 访问。

1) 默认构造函数。
2) 复制构造函数。如果 *thisother 都具有动态类型 std::bad_array_new_length,则 std::strcmp(what(), other.what()) == 0

参数

其他 - 要拷贝的另一个异常对象

std::bad_array_new_length::operator=

bad_array_new_length& operator=( const bad_array_new_length& other ) noexcept;
(C++11 起)

other 的内容替换当前对象的内容。如果 *thisother 都具有动态类型 std::bad_array_new_length,则赋值后 std::strcmp(what(), other.what()) == 0

参数

其他 - 用于赋值的另一个异常对象

返回值

*this

std::bad_array_new_length::what

virtual const char* what() const noexcept;
(C++11 起)
(C++26 起为 constexpr)

返回解释字符串。

返回值

指向一个实现定义的、以 null 结尾的字符串的指针,其中包含解释性信息。该字符串适合转换为 std::wstring 并显示。该指针保证在从其获取的异常对象被销毁之前,或在该异常对象上调用非 const 成员函数(例如复制赋值运算符)之前,始终有效。

在常量求值期间,返回的字符串使用普通字面量编码进行编码。

(C++26 起)

注意

允许但不要求实现重写 what()

继承自 std::bad_alloc

继承自 std::exception

成员函数

销毁异常对象
(std::exception 的虚公共成员函数) [编辑]
[virtual]
返回解释字符串
(std::exception 的虚公共成员函数) [编辑]

[编辑] 注意

特性测试 标准 特性
__cpp_lib_constexpr_exceptions 202411L (C++26) 异常类型的 constexpr

[编辑] 示例

应该抛出 std::bad_array_new_length 的三种情况

#include <climits>
#include <iostream>
#include <new>
 
int main()
{
    try
    {
        int negative = -1;
        new int[negative];
    }
    catch (const std::bad_array_new_length& e)
    {
        std::cout << "1) " << e.what() << ": negative size\n";
    }
 
    try
    {
        int small = 1;
        new int[small]{1,2,3};
    }
    catch (const std::bad_array_new_length& e)
    {
        std::cout << "2) " << e.what() << ": too many initializers\n";
    }
 
    try
    {
        long large = LONG_MAX;
        new int[large][1000];
    } 
    catch (const std::bad_array_new_length& e)
    {
        std::cout << "3) " << e.what() << ": too large\n";
    }
 
    std::cout << "End\n";
}

可能的输出

1) std::bad_array_new_length: negative size
2) std::bad_array_new_length: too many initializers
3) std::bad_array_new_length: too large
End

[编辑] 参阅

分配函数
(函数) [编辑]
内存分配失败时抛出的异常
(类) [编辑]