我将一个中型应用程序从 C 移植到 C++。它不会在任何地方处理异常,这一点不应该改变。
我(错误!)对 C++ 的理解是(直到我昨天艰难地学习它)(默认)new 运算符在出现分配问题时返回 NULL 指针。然而,直到 1993 年(左右)才出现这种情况。现在,它抛出一个 std::bad_alloc 异常。
是否可以在不重写所有内容以在每次调用时使用 std::nothrow 的情况下返回到旧行为?
最佳答案
你可以重载 operator new:
#include <vector>
void *operator new(size_t pAmount) // throw (std::bad_alloc)
{
// just forward to the default no-throwing version.
return ::operator new(pAmount, std::nothrow);
}
int main(void)
{
typedef std::vector<int> container;
container v;
v.reserve(v.max_size()); // should fail
}
关于c++ - 避免 std::bad_alloc。 new 应该返回一个 NULL 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1706776/