命名空间
变体
操作

std::bad_alloc

来自 cppreference.cn
< cpp‎ | memory‎ | 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 对象,该对象带有一个实现定义的空终止字节字符串,可以通过 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

virtual const char* what() const throw();
(直到 C++11)
virtual const char* what() const noexcept;
(自 C++11 起)
(constexpr 自 C++26 起)

返回解释性字符串。

返回值

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

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

(自 C++26 起)

注意

允许但非必须实现 what() 的重载。

继承自 std::exception

成员函数

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

[编辑] 注意

特性测试 Std 特性
__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

[编辑] 参见

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