std::bad_array_new_length
来自cppreference.com
<tbody>
</tbody>

| 在标头 <new> 定义
|
||
class bad_array_new_length; |
(C++11 起) | |
std::bad_array_new_length 是 new 表达式作为异常抛出的对象类型,以报告以下情况下的非法数组长度
- 数组长度为负
- 新数组的总大小将超过实现定义最大值
- 初始化式子句的数量超出要初始化的元素数量
仅数组第一维可生成此异常;第一维外的维数是常量表达式,在编译时得到检查。
继承图
成员函数
(构造函数) |
构造新的 bad_array_new_length 对象 (公开成员函数) |
operator= |
替换 bad_array_new_length 对象 (公开成员函数) |
what |
返回解释字符串 (公开成员函数) |
std::bad_array_new_length::bad_array_new_length
<tbody> </tbody> 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 对象,字符串能通过 what() 访问。
1) 默认构造函数。
2) 复制构造函数。如果
*this 与 other 均拥有动态类型 std::bad_array_new_length,那么 std::strcmp(what(), other.what()) == 0。参数
| other | - | 要复制的另一异常对象 |
std::bad_array_new_length::operator=
<tbody> </tbody> bad_array_new_length& operator=( const bad_array_new_length& other ) noexcept; |
(C++11 起) | |
以 other 的内容赋值。如果 *this 与 other 均拥有动态类型 std::bad_array_new_length,那么赋值后 std::strcmp(what(), other.what()) == 0。
参数
| other | - | 用来赋值的另一异常对象 |
返回值
*this
std::bad_array_new_length::what
<tbody> </tbody>virtual const char* what() const noexcept; |
(C++11 起) (C++26 起为 constexpr) |
|
返回解释字符串。
返回值
指向有由实现定义的解释信息的空终止字符串的指针。该字符串适合转换并显示为 std::wstring。保证该指针至少直到获得它来源的异常对象被销毁,或在该异常对象上调用非 const 成员函数(例如复制赋值运算符)为止一直有效。
|
返回的字符串在常量求值过程中按普通字面量编码。 |
(C++26 起) |
注解
允许但不要求实现覆写 what()。
继承自 std::bad_alloc
继承自 std::exception
成员函数
[虚] |
销毁该异常对象 ( std::exception 的虚公开成员函数)
|
[虚] |
返回解释性字符串 ( 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() << ": 负数大小\n";
}
try
{
int small = 1;
new int[small]{1,2,3};
}
catch (const std::bad_array_new_length& e)
{
std::cout << "2) " << e.what() << ": 过多初始化式\n";
}
try
{
long large = LONG_MAX;
new int[large][1000];
}
catch (const std::bad_array_new_length& e)
{
std::cout << "3) " << e.what() << ": 过大\n";
}
std::cout << "End\n";
}
可能的输出:
1) std::bad_array_new_length: 负数大小
2) std::bad_array_new_length: 过多初始化式
3) std::bad_array_new_length: 过大
End
参阅
| 分配函数 (函数) | |
| 内存分配失败时抛出的异常 (类) |