c++ - 避免 std::bad_alloc。 new 应该返回一个 NULL 指针

标签 c++ c memory-management

我将一个中型应用程序从 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/

相关文章:

c++ - 这是 "*ptr++ = *ptr + a"未定义的行为吗?

c - 为什么我的 for 循环不接受 9 个输入?

objective-c - 在子类的子类中实现 NSCopying

c++ - 为什么不能在 lambda 中使用私有(private)方法?

c++ - 使用 C++ 代码获取 Windows Phone 8.1 中的唯一 DeviceId

c++ - 用DCT解压Opencv屏蔽伪影

c++ - 为什么 C++ 中 char 不被视为数字?

c - 使用 realloc 缩小内存分配

Delphi:为什么 FreeAndNil *真正* nil 我的对象?

c++ - 我怎样才能从 FireBreath 回调到 JavaScript