E-C + + misunderstanding five: Check the return value of new

Source: Internet
Author: User
Tags throw exception

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;
// 其它代码

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.