tags:

views:

116

answers:

4

Possible Duplicate:
Will new return NULL in any case?

Say i have a class Car and i create an object

Car *newcar  = new Car();
if(newcar==NULL) //is it valid to check for NULL if new runs out of memory
{
}
+11  A: 

On a standards-conforming C++ implementation, no. 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).

On some older C++ compilers (especially those that were released before the language was standardized) or in situations where exceptions are explicitly disabled (for example, perhaps some compilers for embedded systems), new may return NULL on failure. Compilers that do this do not conform to the C++ standard.

James McNellis
Exactly! The way to do it in C++ is with try/catch blocks. Here is an example: http://www.cplusplus.com/reference/std/new/bad_alloc/
karlphillip
+1  A: 

By default C++ throws a std::bad_alloc exception when the new operator fails. Therefore the check for NULL is not needed unless you explicitly disabled exception usage.

dark_charlie
... and if you disable exception usage, then the language is no longer C++.
Mike Seymour
+6  A: 

No, new throws std::bad_alloc on allocation failure. Use new(std::nothrow) Car instead if you don't want exceptions.

Georg Fritzsche
+1  A: 

I've seen this many times and wondered why as new will throw a memory exception. I guess it comes from developers who used to work in C and are now C++.

What on earth do you mean? It didn't throw an exception in C, and I'm not sure what behavior you think is sensible if neither of those.
Chuck
"Checking for null," I think he means.
Seamus Campbell