避免使用std :: bad_alloc.new应返回NULL指针

dme*_*ter 6 c c++ memory-management

我将一个中等大小的应用程序从C转移到C++.它不会处理异常,也不会改变.

我(错误!)对C++的理解是(直到我昨天很难学会),(默认)new运算符在分配问题时返回NULL指针.然而,直到1993年(左右)才真实.如今,它会抛出一个std :: bad_alloc异常.

是否有可能在不重写所有内容的情况下返回旧行为,在每次调用时使用std :: nothrow?

GMa*_*ckG 12

你可以重载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
}
Run Code Online (Sandbox Code Playgroud)

  • 这可能会导致致命的失败.标准容器使用allocator(默认为标准分配器)处理内存,并且至少有一个容器在没有内存时会抛出异常,并且不会检查NULL返回值.这也解决了操作员新增类重载的问题.然而,考虑到从C移植代码,这不太可能是问题. (3认同)