C ++ misunderstanding 5: Check the return value of new

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.