C++ 分配器在内存不足时使应用程序崩溃

c++ allocator crashes the application when not enough memory

本文关键字:应用程序 崩溃 内存不足 分配器 C++      更新时间:2023-10-16

当分配器由于内存有限而失败时。应用程序正在崩溃。抛出bad_alloc或返回 nullptr 不会停止崩溃。有人知道吗?

pointer allocator<T>(size_type count) const
{
    void* buffer = new (count * sizeof(T));
    if (!buffer)         // if buffer == nullptr crashes app
        throw bad_alloc; // doing this crashes app
    /* or alternatively
     * try {
     *     void* buffer = new (count * sizeof(T));
     * } catch (const std::exception& e) {
     *     std::cerr << "failed to allocate " << count << std::endl;
     *     return nullptr;
     * }
     */
}

那么该怎么做才能优雅地关闭应用程序并说内存不足呢?

不传播异常需要做各种事情,标准通过指定在异常转义时调用std::terminate来实现。

如果没有程序其余部分的上下文,我们无法知道它是其中之一,还是只是一个例外,留下main

对后者的修复可能看起来像

int main()
{
    try 
    {
        // whatever here
    }
    catch (std::exception & e)
    {
        std::cerr << e.what();
        return EXIT_FAILURE;
    }
}

new运算符自行抛出bad_alloc!所以使用try-catch块:

pointer allocator<T>(size_type count) const
{
    try
    {
        void* buffer = new (count * sizeof(T));
    }
    catch (bad_alloc& ba)
    {
        return nullptr; // or do whatever you have to do to recover
    }
}

有关另一个示例,请参阅此处。