Discuss nullptr and NULL

Source: Internet
Author: User
Tags define null

I have been playing c ++ 11 for the last two days. One of them is the New Keyword nullptr. Here we will discuss the value of nullptr, its application scenarios, and how to simulate nullptr when c ++ 11 is not supported. 1. Why is there nullptr? When we assign an initial value to a pointer, we generally Write FILE * fp = NULL. Here is a NULL definition, which is generally defined as follows: [cpp] # ifdef _ cplusplus # define NULL 0 # else # define NULL (void *) 0) # endif in the C language environment, due to the absence of function overloading and other issues, defining NULL as a void * pointer can solve all problems perfectly. But in the c ++ environment, the situation becomes complicated. First, we cannot write such code FILE * fp = (void *) 0; it is illegal to assign void * directly to a pointer. The Compiler reports an error. We can only write code [cpp] FILE * fp = (FILE *) 0 in this way; // or FILE * fp = 0; so in c ++, NULL is directly defined as an integer 0. In most cases, this does not cause any problems, but in case of heavy loads or template derivation, the compiler will not be able to give the correct results. For example, in the following scenario: [cpp] void call_back_process (CCObject * target, void * data); bind (call_back_process, target, NULL); // The error function type is void *, however, we are bound to an Application Scenario of integer 0 2 and nullptr: if our compiler supports nullptr, we should directly use nullptr to replace NULL macro definitions. They are completely equivalent during normal use. 3. Simulate nullptr implementation: Some compilers do not support nullptr, A New Keyword of c ++ 11. We can also simulate a nullptr [cpp] www.2cto. comconst class nullptr_t_t {public: template <class T> operator T * () const {return 0;} template <class C, class T> operator t c ::*() const {return 0;} private: void operator & () const;} nullptr_t = {};# undef NULL # define NULL nullptr_t

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.