# Operator New and Delete - Unnecessary Conditions
I've seen following constructs many times in C++ code:
MyClass* obj = new MyClass();
if(obj == nullptr)
// Handle allocation error.
if(obj != nullptr)
Both of these conditions are unnecessary. Strictly speaking they are not a bug - program will run correctly, but they make no sense. If you used to write any of these, you should know that:
new doesn't return null on failed allocation. By default it throws an exception of type
std::bad_alloc in this case, so this is what you should handle if you really care about the state of your program after it runs out of memory (or if the allocated object is particularly big).
There is also special
nothrow version of the
new operator that returns null on failure, but you must call it explicitly. An alternative would be to overload
new operator (global or for particular class) to change its behavior. But again, this is not what happens by default.
Note this is different behavior than
malloc function from C. Obviously there are no exceptions in C language, so this function just returns null on failure.
delete doesn't crash when you pass null pointer to it - it just does nothing, so the check for not-null is already inside, you don't have to write it. Of course trying to delete object from any non-null address that was already freed or is just invalid address still crashes, or causes other undefined behavior.
Note this is the same behavior as
free function from C - it also accepts null pointer.