std::bad_array_new_length
来自 cppreference.cn
定义于头文件 <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
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=
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
virtual const char* what() const noexcept; |
(自 C++11 起) (constexpr 自 C++26 起) |
|
返回解释性字符串。
返回值
指向实现定义的空终止字符串的指针,其中包含解释性信息。 该字符串适合转换为 std::wstring 并显示。 指针保证有效,至少在从中获取它的异常对象被销毁之前,或者直到调用异常对象上的非 const 成员函数(例如,复制赋值运算符)为止。
返回的字符串在常量求值期间使用普通的字面编码进行编码。 |
(自 C++26 起) |
注解
允许但不需要实现来重写 what()
。
继承自 std::bad_alloc
继承自 std::exception
成员函数
[virtual] |
销毁异常对象 ( std::exception 的虚公有成员函数) |
[virtual] |
返回解释性字符串 ( std::exception 的虚公有成员函数) |
[编辑] 注解
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__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
[编辑] 参见
分配函数 (函数) | |
内存分配失败时抛出的异常 (类) |