Before talking about this issue, I would like to talk about the style of this paper first, which is also my writing style. Usually, I do not come up with concepts and principles like textbooks. I like to introduce a knowledge by using known and understandable questions.

For example, in this article, many people may not know about NULlPTR or why it was introduced, but nullPTR is known, and nullPTR introduction is often much more acceptable.

What can you get from this article

  • You can see a new feature called NullPtr that is extremely useful and difficult

  • Can you see why C++ uses nullptr instead of NULL

  • You can use the sluttier NULlPTR for future programming

(This article for small white, big guy do not spray)

The problem described

In the past, we used to initialize Pointers with NULL, which seemed fine at the time!

Void * PTR = NULL;Copy the code

However, in a sense, traditional C++ treats NULL and 0 as the same thing, depending on how the compiler defines NULL. Some compilers will define NULL as ((void*)0), while others will define it as 0 directly.

So what’s the problem with that?

C++ without the implicit conversion of void * has to define NULL as 0. This still creates a new problem, as defining NULL as zero leads to confusion over overloaded features in C++. Consider the following two functions:

void Function(char *);
void Function(int);
Copy the code

If the compiler defines NULL as 0, Function(NULL) will call void Function(int) based on the overloaded nature;

This is obviously unreasonable!

So nullPTR came out of nowhere, painless, and became my favorite new feature to use.

nullptr

C++11 introduced the nullptr keyword to distinguish between null Pointers and zeros. Nullptr is of type NULlPTR_T, which can be implicitly converted to any pointer or member pointer type and can be compared equally or unequally with them.

Code sample

#include<iostream> void Function(char *) { std::cout << "Function(char*) is called" << std::endl; } void Function(int i) { std::cout << "Function(int) is called" << std::endl; } void main () {/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / / verify the compiler will null position 0 or 0 (void *) /***************************************/ if (std::is_same<decltype(NULL), decltype(0)>::value) { std::cout << "NULL == 0" << std::endl; } if (std::is_same<decltype(NULL), decltype((void*)0)>::value) { std::cout << "NULL == (void *)0" << std::endl; } if (std::is_same<decltype(NULL), std::nullptr_t>::value) { std::cout << "NULL == nullptr" << std::endl; } Function(0); Function(int) Function(NULL); // call Function(int) Function(nullptr); // call Function(char*)}Copy the code

conclusion

Use nullptr directly when initializing a pointer.