Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

What about not using nothrow argument on new operator? Does it also returns null?

The C++ standard (§18.4.1.1) defines operator new as:

void* operator new (std::size_t size) throw (std::bad_alloc);

So the standard behavior of new which takes one argument is to throw a std::bad_alloc in case of failure. The standard also defines a nothrow new version which takes two parameters:

void* operator new(std::size_t size, const std::nothrow_t&) throw();

This version returns a NULL in case of failure, but note that to use this version you explicitly need to pass an additional parameter to the new operator.


When should you use nothrow version?

Ideally, You should always use the standard version of new which throws a bad_alloc. You should stick to that recommendation always. However, in some situations you might be forced to use the nothrow version. Some of such situations are:

  • You are working with older C++ compilers (released before the language was standardized) which do not support exceptions.
  • The target platforms where exceptions are explicitly disabled (ex: embedded systems) or not guaranteed to work correctly.
  • Post 1990's the standard behavior of new was to return NULL, if you are working with a lot of legacy code which relies on this behavior.

When new is not able to allocate memory it throws an exception bad_alloc which will make your program to crash in an unusual way if this exception is not handled.If we want avoid this situation we can either use nothrow which is the argument for the overloaded function new or can catch the exception. nothrow will return null when out of memory and the programmer can decide what to do at this point.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top