命名空间
变体
操作

std::bad_alloc

来自 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_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 对象,带有一个实现定义的以 null 结尾的字节字符串,该字符串可通过 what() 访问。

1) 默认构造函数。
2) 拷贝构造函数。如果 *thisother 都具有动态类型 std::bad_alloc,则 std::strcmp(what(), other.what()) == 0(C++11 起)

参数

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

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 起)

参数

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

返回值

*this

std::bad_alloc::what

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

返回解释字符串。

返回值

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

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

(C++26 起)

注意

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

继承自 std::exception

成员函数

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

[编辑] 注释

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

[编辑] 示例

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

可能的输出

Allocation failed: std::bad_alloc

[编辑] 参阅

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