c++ - 处理 bad_alloc 时使用 cerr 是否安全?

标签 c++ exception-handling

这样使用 std::cerr 安全吗?

try 
{
      Something();
} 
catch(std::bad_alloc) 
{
    cerr << "Out of memory!";
}

它是否使用动态内存?如果失败,它会抛出异常还是什么都不输出?

最佳答案

简单案例

有一个失败的大分配 - 可能是由于程序员的错误 -

int main() 
{

    try {
        std::size_t bytesToAllocate;
        std::cin >> bytesToAllocate;

        std::unique_ptr<char> ptr { new char[bytesToAllocate - 1] };
        // ops, if user enters 0 or extraction fails we get 
        // std::numeric_limits<std::size_t>::max() -1 bytes to allocate

    } catch (const std::bad_alloc& e) {
            std::cerr << "Failed to allocate memory.\n";
    }
}

在这里,即使 new 失败,我们肯定还有更多的内存,因为之前没有使用过。

现实案例

如果由于某些未指定的原因,字符插入失败,则启用内部 failbitsetstate(std::ios_base::failbit) 并且,如果 exception is set 用于failbit,抛出异常。此外,如果在插入期间抛出异常,则设置 badbit,如果在 badbit 上设置了 exception,则会重新抛出异常。

但是,据我所知,它是未被发现的,因此未指定此类操作是否分配内存以及它是如何完成的。如果异常传播的整个过程在那种情况下完全可能,您的程序可能会因为内存不足保护而被终止,因此没有机会捕获异常。

关于c++ - 处理 bad_alloc 时使用 cerr 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32699874/

相关文章:

c++ - 在异常处理中避免复制

java - 如果我不是,谁在调用 Java 线程的 interrupt() 方法?

exception-handling - 在 OCaml 中模拟 try-with-finally

c++ - 如何覆盖常规 malloc,以便在内存泄漏打印输出中打印行号

c++ - 在 std::set 上并行化缺少 operator-() 的 cilk_for 错误

c++ - Qt文本浏览器不能实时显示

c++ - 使用前向引用

c++ - 如何重载operator<<以与boost::program_options默认值输出一起使用?

c# - 如何在 C# 应用程序中从 C++ 调用抛出 C# 函数,以便正确展开 C++ 堆栈?

exception-handling - 在 Vimscript 中 try catch