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?
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?
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
.No need to check for null, in general. An allocation failure will throw a std::bad_alloc exception, which you can deal with if you like.
The standard indicates:
"If an allocation function declared with a non-throwing exception-specification (15.4) fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall indicate failure only by throwing an exception of a type that would match a handler (15.3) of type std::bad_alloc (18.6.2.1)."
YMMV depending on how standards-compliant your compiler actually is. I think most modern c++ compilers should be embarrassed to do it differently. :)
I don't think you should check everytime for the new Object to be created, usually new operator doesn't fails in creating the object unless you have some coding issues.
The only thing you always have to consider is to have a working constructor, which set up the new object correctly.
Yes. If it does fail on a modern OS with virtual memory, it's usually because of a bug in the application (e.g., allocating an insane amount of memory) or a really bad fragmentation problem.
If new
fails, it will throw a std::bad_alloc
exception. It's up to your application to decide if it wants to catch that exception and try something else. It depends a lot on the type of application.
However, some people use a non-standard version of new
that returns a null pointer instead of throwing an exception. You'd use the same criteria for that as you would for old-fashioned malloc
. It depends on the type of allocation. Often, crashing is the appropriate thing to do if you cannot complete an allocation, so not checking for NULL
can be an acceptable decision.