std::bad_alloc_C++中文网

class bad_alloc;

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

cpp/error/exception

std-bad alloc-inheritance.svg

继承图

成员函数

构造 bad_alloc 对象
(公开成员函数)
替换一个 bad_alloc 对象
(公开成员函数)
返回解释性字符串
(公开成员函数)

std::bad_alloc::bad_alloc

bad_alloc() throw();

(C++11 前)

bad_alloc() noexcept;

(C++11 起)

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

参数

(无)

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 的内容赋值。

参数

返回值

*this

std::bad_alloc::what

virtual const char* what() const throw();

(C++11 前)

virtual const char* what() const noexcept;

(C++11 起)

返回解释性字符串。

参数

(无)

返回值

指向有解释性信息的空终止字符串的指针。

继承自 std::exception

成员函数

析构该异常对象
(std::exception 的虚公开成员函数)
返回解释性字符串
(std::exception 的虚公开成员函数)

示例

#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

参阅