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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No,
objcannot beNULL.If
newfails, it will throw astd::bad_allocexception. If no exception was thrown,objis guaranteed to point to a fully initialized instance ofObject.There is a variant of
newthat doesn’t throw an exceptionIn this case,
objwill beNULLifnewfails, and thestd::bad_allocexception will not be thrown (thoughObject‘s constructor can obviously still throw exceptions).On some older compilers,
newmight not throw an exception and rather returnNULLinstead, but this is not standards-compliant behaviour.If you’ve overloaded
operator new, it might behave differently depending on your implementation.