Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should one always check, if the new operator worked?

I have two questions about the new operator:

  1. Can the new operator fail to allocate memory?

  2. Should one test after every use of new, if there really was an object created?

like image 383
Fabian Avatar asked Mar 04 '11 18:03

Fabian


People also ask

What happens if new operator fails?

What happens when new fails? Explanation: While creating new objects, the new operator may fail because of memory errors or due to permissions. At that moment the new operator returns zero or it may throw an exception. The exception can be handled as usual.

What is the main purpose of using the new operator?

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

Can new return Nullptr?

The ordinary form of new will never return NULL ; if allocation fails, a std::bad_alloc exception will be thrown (the new (nothrow) form does not throw exceptions, and will return NULL if allocation fails).


2 Answers

operator new throws a std::bad_alloc exception on failure, unless you're explicitly using the nothrow version. Therefore, don't check the return value: If you arrive at the next line after the constructor call, you can safely assume that the constructor succeeded.

But do wrap the appropriately-scoped branch of your code in a try-catch block: Usually not right directly around the new call, but somewhere up the line where you can call off everything that depends on the allocation, and nothing else.

UPDATE: But see also Jonathan Leffler's comment below about the nothrow variant of new.

like image 76
15ee8f99-57ff-4f92-890c-b56153 Avatar answered Sep 24 '22 06:09

15ee8f99-57ff-4f92-890c-b56153


  1. Yes, new can fail to allocate memory, but by default it throws an exception when it does fail.
  2. You only need to check the result if you use the no-throw variant of new.
like image 32
Jonathan Leffler Avatar answered Sep 23 '22 06:09

Jonathan Leffler