First of all, this misunderstanding is only set up in C + +, here is just the title of "C + + misunderstanding."
As we all know, when using a function that allocates memory, such as malloc/calloc, it is important to check that its return value is a "null pointer" (that is, to check whether the allocated memory is successful), which is good programming practice and is necessary to write a reliable program. However, if you simply apply this trick to new, it may not be correct. I often see code similar to this:
int* p = new int[SIZE];
if ( p == 0 ) // 检查 p 是否空指针
return -1;
// 其它代码
In fact, the IF (p = 0) here is completely meaningless. In C + +, if new allocates memory failure, the default is to throw an exception. So, if the assignment succeeds, p = 0 will never set up, and if the allocation fails, it will not execute if (p = = 0), because when the allocation fails, new throws an exception to skip the following code. If you want to check whether new is successful, you should catch the exception:
try {
int* p = new int[SIZE];
// 其它代码
} catch ( const bad_alloc& e ) {
return -1;
}
It is said that some old compilers, new if the allocation of memory failed, is not thrown exception (presumably because then C + + has not joined the exception mechanism), but as malloc, return the null pointer. But I've never met new. Returns the null pointer.
Of course, standard C + + also provides a way to suppress the new throw exception and return the null pointer:
int* p = new (std::nothrow) int; // 这样如果 new 失败了,就不会抛出异常,而是返回空指针
if ( p == 0 ) // 如此这般,这个判断就有意义了
return -1;
// 其它代码