Search code examples
c++out-of-memorynothrow

C++ : What shall it be returned when out of memory?


When I code as below, it'll return 'null' and no exception occured.

Char* pStr = new(std::nothrow)Char(10);

What about not using 'nothrow' argument on new operator? Does it also returns 'null'? If so, why is it recommended to use 'nothrow' argument?

Char* pStr = new Char(10);

Thanks for your time.


Solution

  • new will throw an exception if it fails, unless you specify nothrow, in which case it will return nullptr if it fails.

    As for why nothrow is ever used: On some systems, exceptions aren't supported (or are badly supported) (this can be particularly true on gaming consoles). So it's best to not even use them at all. This is just one example when nothrow may be used.