NULL in creation

When writing C ++, let's say the following line of code:

Object* obj = new Object(); 

If this line compiles and does not raise exceptions or other visible runtime problems, could it be NULL right after this line is executed?

+7
source share
4 answers

No, obj cannot be NULL .

If new fails, it throws a std::bad_alloc . If no exception has been thrown, obj guaranteed to point to a fully initialized instance of Object .

There is a new option that does not throw an exception

 Object *obj = new(nothrow) Object(); 

In this case, obj will be NULL if new fails and the std::bad_alloc not std::bad_alloc (although the Object constructor can obviously still throw exceptions).

In some older compilers, new cannot throw an exception and return NULL instead, but this does not conform to the standard of behavior.

If you overloaded operator new , this may behave differently depending on your implementation.

+14
source

No, your exact string cannot behave this way. obj will always point to valid memory unless exceptions are thrown. The following line, however, will return 0 if memory cannot be allocated:

 Object* obj = new (std::nothrow) Object(); 
+4
source

new throws std::bad_alloc - selection was not performed. Therefore, you must catch this exception.
You should use nothrow new if you want to check for NULL after new.

+3
source

No, unless you have turned off the exceptions or overloaded std::new to do something different from the standard (which std::bad_alloc on error).

(I'm not sure how std::new behaves when exceptions are disabled, but a discussion of this is available here ...)

+2
source

All Articles