C + + learning Note NULL vs NULLPTR

Source: Internet
Author: User

Write in front

With the advent of the C++11 standard, C + + norms are increasingly rigorous, in reducing the two semantics of language, the C + + committee did a lot of efforts. As for those who have learned c++98 or 03 of the standard, think C + + sucks people, I just want to send four words, sit idle.

NULL vs nullptr

In the past, if we were to indicate that a pointer was empty, we would definitely say this:

int *p = NULL;

However, have you ever thought that this is problematic, such as the following code:

 #include <iostream> #include <string>using namespace std; void func (int* num) {cout <<  "This is the PTR function ..." << Endl;} void func (int num) {cout < <  "This is the normal function ..." << Endl; void Main (int argc, char** argv) { Func (NULL);}                

What will the program output?? I asked a lot of people, their unanimous answer is: Output This is the PTR function ... Ah, don't forget to bring a taunt. In fact, the output here is:

In fact, when the compiler interprets the program, NULL will be interpreted directly as 0, so the parameter here is not what everyone thought of NULL, the parameter has been secretly replaced by the compiler 0,0 is an integer ah, so the call is the second function. So some programmers also suggested that null be replaced by 0, which would reduce the difficulty of later maintenance. But how do I invoke the first function? There are many solutions on the Web (mostly written using previous standards).

C++11 the emergence of a complete solution to this problem, nullptr in c++11 is to represent the null pointer, can not be converted into a number (the specific bottom is how to achieve, we can look at the API, the author said not understand t_t), then we try again, see this time what is the result?

What, see the results.

C + + learning Note NULL vs NULLPTR

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.