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 problem开发者_JAVA技巧s, 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();
new
throws std::bad_alloc
is allocation was not sucessful. So you should catch that exception.
You should use nothrow new if you want to be checking for NULL
after new.
No, unless you disabled exceptions or overloaded std::new
to do something other than the standard one (which throws std::bad_alloc
on failure).
(I'm not sure how std::new
behaves when exceptions are disabled, but a discussion on this is available here...)
精彩评论