Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NULL in instantiation

Tags:

c++

null

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

Object* obj = new Object(); 

If this line both compiles and does not cause exceptions or any other visible runtime problems, can obj be NULL right after this line was executed?

like image 874
user181218 Avatar asked Jun 12 '11 07:06

user181218


2 Answers

No, obj cannot be NULL.

If new fails, it will throw a std::bad_alloc exception. If no exception was thrown, obj is guaranteed to point to a fully initialized instance of Object.

There is a variant of new that doesn't throw an exception

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

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

On some older compilers, new might not throw an exception and rather return NULL instead, but this is not standards-compliant behaviour.

If you've overloaded operator new, it might behave differently depending on your implementation.

like image 68
Sven Avatar answered Oct 21 '22 05:10

Sven


No, your exact line cannot behave like that. obj will always point to valid memory if no exceptions are thrown. The following line, though, will return 0 if the memory could not be allocated:

Object* obj = new (std::nothrow) Object();
like image 21
Xeo Avatar answered Oct 21 '22 05:10

Xeo