首页 > 解决方案 > c++分配器在内存不足时使应用程序崩溃

问题描述

当分配器由于内存有限而失败时。该应用程序正在崩溃。抛出bad_alloc或 return 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;
     * }
     */
}

那么如何优雅地关闭应用并说内存不足呢?

标签: c++c++11stl

解决方案


有很多事情需要不传播异常,标准通过指定std::terminate如果异常会逃逸则调用它来做到这一点。

如果没有您程序其余部分的上下文,我们无法知道它是其中之一,还是只是一个异常离开main

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

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

推荐阅读