1. nullptr C++

Why nullptr ? what is nullptr ?







But we already have NULL why nullptr ?

Well the problem is how to distinguish between NULL and 0? we have #define NULL 0. The NULL pointer and an integer 0 cannot be distinguished well for overload resolution. For example, given two overloaded functions



The call f(0) unambiguously resolves to f(int).

There is no way to write a call to f(char*) with a null pointer value without writing an explicit cast (i.e., f((char*)0)) or using a named variable.

Naming NULL

Further, programmers have often requested that the null pointer constant have a name (rather than just 0).

This is one reason why the macro NULL exists, although that macro is insufficient. (If the null pointer constant had a type-safe name, this would also solve the previous problem as it could be distinguished from the integer 0 for overload resolution and some error detection.)

To avoid these problems, 0 must mean only one thing (an integer value), and we need to have a different name to express the other (a null pointer) and hence we have nullptr.

It 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.

It improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously.

Make C++ easier to learn.

Finally C++ Core guideline says:

ES.47: Use nullptr rather than 0 or NULL.

To avoid problems use nullptr if you are not using already.



Comments

  1. In the beginning there was the nullptr and the architect said, "Let there be data."

    ReplyDelete

Post a Comment

Popular posts from this blog

3. Template type deduction when template parameter is neither a pointer nor a reference

2. Why should someone Learn C++ ?