For a friend who has learned C, you should know that when using a function such as malloc/calloc, it is important to check whether the return value is a "null pointer" (that is, to check whether the allocated memory is successful), which is good programming practice and 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 [MAXSIZE]
if (p = = 0)//Check whether the P pointer is an empty
return-1;
Other code
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 [MAXSIZE]
}
catch (Bad_alloc & exp)
{
cerrr<<exp.what () < <endl;
}
But some programmers are not used to catching exceptions, and standard C + + provides a way to return null pointers without throwing an exception.
int * p = new (std::nothrow) int [MAXSIZE]
if (p = = 0)//Check whether the P pointer is empty
return-1;
Other code