I have two questions about the new operator:
Can the new operator fail to allocate memory?
Should one test after every use of new, if there really was an object created?
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.
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.
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).
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.
new
can fail to allocate memory, but by default it throws an exception when it does fail.new
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With