Search code examples
c++new-operator

Is it useful to test the return of "new" in C++?


I usually never see test for new in C++ and I was wondering why.

Foo *f = new Foo;

// f is assumed as allocated, why usually, nobody test the return of new?


Solution

  • As per the current standard, the argumentless version of new never returns NULL, it throws a std::bad_alloc instead. If you don't want new to throw(as per the old standard) but rather return NULL you should pass std::nothrow, such as

    Foo* foo = new(std::nothrow) Foo;
    

    Of course, if you have a very old or possibly broken toolchain it might not follow the standard.