From: http://cpp.ga-la.com/html/3/3/0709/318.htm
First of all, I want to clarify that this misunderstanding is only true for C ++. Here it is just a reference to the "C/C ++ misunderstanding.
We all know that when using functions such as malloc/calloc to allocate memory, you must check whether the returned value is a "Null Pointer" (that is, whether the operation for allocating memory is successful ), this is a good programming habit and is also necessary to write reliable programs. However, if you simply apply this trick to new, it may not be correct. I often see code like this:
Int * P = new int [size];
If (P = 0) // check if p is a null pointer
Return-1;
// Other code
In fact, the IF (P = 0) Here is completely meaningless. In C ++, if the new memory allocation fails, the default value isThrow an exception. Therefore, if the allocation is successful, P = 0 will never be true. If the allocation fails, if (P = 0) will not be executed, because when the allocation fails, new willThrow an exception to skip the code. If you want to check whether new is successfulCapture exceptions:
Try {
Int * P = new int [size];
// Other code
} Catch (const bad_alloc & E ){
Return-1;
}
It is said that in some old compilers, if the new compiler fails to allocate memory, no exception will be thrown (probably because C ++ didn't add the exception mechanism at that time), but it is the same as malloc, returns a null pointer. However, I have never encountered a null pointer returned by new.
Of course, the standard C ++ also provides a methodSuppress new and throw an exceptionAnd returns a null pointer:
Int * P = new (STD: nothrow) int; // in this way, if new fails, no exception is thrown, but a null pointer is returned.
If (P = 0) // this makes sense.
Return-1;
// Other code