NULL vs nullptr (Why was it replaced?)

C++PointersNullNullptr

C++ Problem Overview


I know that in C++ 0x or NULL was replaced by nullptr in pointer-based applications. I'm just curious of the exact reason why they made this replacement?

In what scenario is using nullptr over NULL beneficial when dealing with pointers?

C++ Solutions


Solution 1 - C++

nullptr has type std::nullptr_t. It's implicitly convertible to any pointer type. Thus, it'll match std::nullptr_t or pointer types in overload resolution, but not other types such as int.

0 (aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:

f(int);
f(foo *);

(Thanks to Caleth pointing this out in the comments.)

Solution 2 - C++

You can find a good explanation of why it was replaced by reading A name for the null pointer: nullptr, to quote the paper:

>This problem falls into the following categories: > > * Improve support for library building, by providing a way for users to write less ambiguous code, so that over time library writers will not need to worry about overloading on integral and pointer types. > > * Improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously. > > * Make C++ easier to teach and learn.

Solution 3 - C++

Here is Bjarne Stroustrup's wordings,

> In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days. > > If you have to name the null pointer, call it nullptr; that's what > it's called in C++11. Then, "nullptr" will be a keyword.

Solution 4 - C++

One reason: the literal 0 has a bad tendency to acquire the type int, e.g. in perfect argument forwarding or more in general as argument with templated type.

Another reason: readability and clarity of code.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRiptyde4View Question on Stackoverflow
Solution 1 - C++Joe ZView Answer on Stackoverflow
Solution 2 - C++Shafik YaghmourView Answer on Stackoverflow
Solution 3 - C++DeidreiView Answer on Stackoverflow
Solution 4 - C++Cheers and hth. - AlfView Answer on Stackoverflow