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?
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.
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();
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