std::bad_alloc

来自cppreference.com
< cpp‎ | memory‎ | new
 
 
 
内存管理库
(仅用于阐述*)
分配器
未初始化内存算法
受约束的未初始化内存算法
内存资源
未初始化存储(C++20 前)
(C++17 弃用)
(C++17 弃用)
垃圾收集器支持(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
 
 
在标头 <new> 定义
class bad_alloc;

std::bad_alloc分配函数作为异常抛出的对象类型,以报告存储分配失败。

cpp/error/exceptionstd-bad alloc-inheritance.svg
关于这幅图像

继承图

目录

[编辑]成员函数

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

std::bad_alloc::bad_alloc

(1)
bad_alloc()throw();
(C++11 前)
bad_alloc()noexcept;
(C++11 起)
(2)
bad_alloc(const bad_alloc& other )throw();
(C++11 前)
bad_alloc(const bad_alloc& other )noexcept;
(C++11 起)

构造新的拥有实现定义的空终止字节字符串的 bad_alloc 对象,字符串能通过 what() 访问。

1) 默认构造函数。
2) 复制构造函数。如果 *thisother 均拥有动态类型 std::bad_alloc,那么 std::strcmp(what(), other.what())==0(C++11 起)

参数

other - 要复制的另一异常对象

std::bad_alloc::operator=

bad_alloc& operator=(const bad_alloc& other )throw();
(C++11 前)
bad_alloc& operator=(const bad_alloc& other )noexcept;
(C++11 起)

other 的内容赋值。如果 *thisother 均拥有动态类型 std::bad_alloc,那么赋值后 std::strcmp(what(), other.what())==0(C++11 起)

参数

other - 用来赋值的另一异常对象

返回值

*this

std::bad_alloc::what

virtualconstchar* what()constthrow();
(C++11 前)
virtualconstchar* what()constnoexcept;
(C++11 起)
(C++26 起为 constexpr)

返回解释字符串。

返回值

指向有由实现定义的解释信息的空终止字符串的指针。该字符串适合转换并显示为 std::wstring。保证该指针至少直到获得它来源的异常对象被销毁,或在该异常对象上调用非 const 成员函数(例如复制赋值运算符)为止一直有效。

返回的字符串在常量求值过程中按普通字面量编码。

(C++26 起)

注解

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

继承自 std::exception

成员函数

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

[编辑]注解

功能特性测试标准功能特性
__cpp_lib_constexpr_exceptions202411L(C++26)constexpr 的异常类型

[编辑]示例

#include <iostream>#include <new>   int main(){try{while(true){ new int[100000000ul];}}catch(const std::bad_alloc& e){std::cout<<"分配失败: "<< e.what()<<'\n';}}

可能的输出:

分配失败: std::bad_alloc

[编辑]参阅

分配函数
(函数)[编辑]
close