这样使用 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
失败,我们肯定还有更多的内存,因为之前没有使用过。
现实案例
如果由于某些未指定的原因,字符插入失败,则启用内部 failbit
即 setstate(std::ios_base::failbit)
并且,如果 exception
is set 用于failbit
,抛出异常。此外,如果在插入期间抛出异常,则设置 badbit
,如果在 badbit
上设置了 exception
,则会重新抛出异常。
但是,据我所知,它是未被发现的,因此未指定此类操作是否分配内存以及它是如何完成的。如果异常传播的整个过程在那种情况下完全可能,您的程序可能会因为内存不足保护而被终止,因此没有机会捕获异常。
关于c++ - 处理 bad_alloc 时使用 cerr 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32699874/