What are the advantages of using nullptr?

浪子不回头ぞ 提交于 2019-12-27 10:33:04

问题


This piece of code conceptually does the same thing for the three pointers (safe pointer initialization):

int* p1 = nullptr;
int* p2 = NULL;
int* p3 = 0;

And so, what are the advantages of assigning pointers nullptr over assigning them the values NULL or 0?


回答1:


In that code, there doesn't seem to be an advantage. But consider the following overloaded functions:

void f(char const *ptr);
void f(int v);

f(NULL);  //which function will be called?

Which function will be called? Of course, the intention here is to call f(char const *), but in reality f(int) will be called! That is a big problem1, isn't it?

So, the solution to such problems is to use nullptr:

f(nullptr); //first function is called

Of course, that is not the only advantage of nullptr. Here is another:

template<typename T, T *ptr>
struct something{};                     //primary template

template<>
struct something<nullptr_t, nullptr>{};  //partial specialization for nullptr

Since in template, the type of nullptr is deduced as nullptr_t, so you can write this:

template<typename T>
void f(T *ptr);   //function to handle non-nullptr argument

void f(nullptr_t); //an overload to handle nullptr argument!!!

1. In C++, NULL is defined as #define NULL 0, so it is basically int, that is why f(int) is called.




回答2:


C++11 introduces nullptr, it is known as the Null pointer constant and It improves type safety and resolves ambiguous situations unlike the existing implementation dependent null pointer constant NULL. To be able to understand the advantages of nullptr. we first need to understand what is NULL and what are the problems associated with it.


What is NULL exactly?

Pre C++11 NULL was used to represent a pointer that has no value or pointer that does not point to anything valid. Contrary to the popular notion NULL is not a keyword in C++. It is an identifier defined in standard library headers. In short you cannot use NULL without including some standard library headers. Consider the Sample program:

int main()
{ 
    int *ptr = NULL;
    return 0;
}

Output:

prog.cpp: In function 'int main()':
prog.cpp:3:16: error: 'NULL' was not declared in this scope

The C++ standard defines NULL as an implementation defined macro defined in certain standard library header files. The origin of NULL is from C and C++ inherited it from C. The C standard defined NULL as 0 or (void *)0. But in C++ there is a subtle difference.

C++ could not accept this specification as it is. Unlike C, C++ is a strongly typed language (C does not require explicit cast from void* to any type, while C++ mandates a explicit cast). This makes the definition of NULL specified by C standard useless in many C++ expressions. For example:

std::string * str = NULL;         //Case 1
void (A::*ptrFunc) () = &A::doSomething;
if (ptrFunc == NULL) {}           //Case 2

If NULL was defined as (void *)0, neither of above expressions would work.

  • Case 1: Will not compile because a automatic cast is needed from void * to std::string.
  • Case 2: Will not compile because cast from void * to pointer to member function is needed.

So unlike C, C++ Standard mandated to define NULL as numeric literal 0 or 0L.


So what is the need for another null pointer constant when we have NULL already?

Though the C++ Standards committee came up with a NULL definition which will work for C++, this definition had its own fair share of problems. NULL worked well enough for almost all scenarios but not all. It gave surprising and erroneous results for certain rare scenarios. For example:

#include<iostream>
void doSomething(int)
{
    std::cout<<"In Int version";
}
void doSomething(char *)
{
   std::cout<<"In char* version";
}

int main()
{
    doSomething(NULL);
    return 0;
}

Output:

In Int version

Clearly, the intention seems to be to call the version which takes char* as the argument, but as the output shows the function which takes an int version gets called. This is because NULL is a numeric literal.

Furthermore, since it is implementation-defined whether NULL is 0 or 0L, there can lot of confusion in function overload resolution.

Sample Program:

#include <cstddef>

void doSomething(int);
void doSomething(char *);

int main()
{
  doSomething(static_cast <char *>(0));    // Case 1
  doSomething(0);                          // Case 2
  doSomething(NULL)                        // Case 3
}

Analyzing the above snippet:

  • Case 1: calls doSomething(char *) as expected.
  • Case 2: calls doSomething(int) but maybe char* version was be desired because 0 IS also a null pointer.
  • Case 3: If NULL is defined as 0, calls doSomething(int) when perhaps doSomething(char *) was intended, perhaps resulting in logic error at runtime. If NULL is defined as 0L, the call is ambiguous and results in compilation error.

So, depending on implementation, the same code can give various outcomes, which is clearly undesired. Naturally, the C++ standards committee wanted to correct this and that is the prime motivation for nullptr.


So what is nullptr and how does it avoid the problems of NULL?

C++11 introduces a new keyword nullptr to serve as null pointer constant. Unlike NULL, its behavior is not implementation-defined. It is not a macro but it has its own type. nullptr has the type std::nullptr_t. C++11 appropriately defines properties for the nullptr to avoid the disadvantages of NULL. To summarize its properties:

Property 1: it has its own type std::nullptr_t, and
Property 2: it is implicitly convertible and comparable to any pointer type or pointer-to-member type, but
Property 3: it is not implicitly convertible or comparable to integral types, except for bool.

Consider the following example:

#include<iostream>
void doSomething(int)
{
    std::cout<<"In Int version";
}
void doSomething(char *)
{
   std::cout<<"In char* version";
}

int main()
{
    char *pc = nullptr;      // Case 1
    int i = nullptr;         // Case 2
    bool flag = nullptr;     // Case 3

    doSomething(nullptr);    // Case 4
    return 0;
}

In the above program,

  • Case 1: OK - Property 2
  • Case 2: Not Ok - Property 3
  • Case 3: OK - Property 3
  • Case 4: No confusion - Calls char * version, Property 2 & 3

Thus introduction of nullptr avoids all the problems of good old NULL.

How and where should you use nullptr?

The rule of thumb for C++11 is simply start using nullptr whenever you would have otherwise used NULL in the past.


Standard References:

C++11 Standard: C.3.2.4 Macro NULL
C++11 Standard: 18.2 Types
C++11 Standard: 4.10 Pointer conversions
C99 Standard: 6.3.2.3 Pointers




回答3:


The real motivation here is perfect forwarding.

Consider:

void f(int* p);
template<typename T> void forward(T&& t) {
    f(std::forward<T>(t));
}
int main() {
    forward(0); // FAIL
}

Simply put, 0 is a special value, but values cannot propagate through the system- only types can. Forwarding functions are essential, and 0 can't deal with them. Thus, it was absolutely necessary to introduce nullptr, where the type is what is special, and the type can indeed propagate. In fact, the MSVC team had to introduce nullptr ahead of schedule after they implemented rvalue references and then discovered this pitfall for themselves.

There are a few other corner cases where nullptr can make life easier- but it's not a core case, as a cast can solve these problems. Consider

void f(int);
void f(int*);
int main() { f(0); f(nullptr); }

Calls two separate overloads. In addition, consider

void f(int*);
void f(long*);
int main() { f(0); }

This is ambiguous. But, with nullptr, you can provide

void f(std::nullptr_t)
int main() { f(nullptr); }



回答4:


Basics of nullptr

std::nullptr_t is the type of the null pointer literal, nullptr. It is a prvalue/rvalue of type std::nullptr_t. There exist implicit conversions from nullptr to null pointer value of any pointer type.

The literal 0 is an int, not a pointer. If C++ finds itself looking at 0 in a context where only a pointer can be used, it’ll grudgingly interpret 0 as a null pointer, but that’s a fallback position. C++’s primary policy is that 0 is an int, not a pointer.

Advantage 1 - Remove ambiguity when overloading on pointer and integral types

In C++98, the primary implication of this was that overloading on pointer and integral types could lead to surprises. Passing 0 or NULL to such overloads never called a pointer overload:

   void fun(int); // two overloads of fun
    void fun(void*);
    fun(0); // calls f(int), not fun(void*)
    fun(NULL); // might not compile, but typically calls fun(int). Never calls fun(void*)

The interesting thing about that call is the contradiction between the apparent meaning of the source code (“I am calling fun with NULL-the null pointer”) and its actual meaning (“I am calling fun with some kind of integer— not the null pointer”).

nullptr’s advantage is that it doesn’t have an integral type. Calling the overloaded function fun with nullptr calls the void* overload (i.e., the pointer overload), because nullptr can’t be viewed as anything integral:

fun(nullptr); // calls fun(void*) overload 

Using nullptr instead of 0 or NULL thus avoids overload resolution surprises.

Another advantage of nullptr over NULL(0) when using auto for return type

For example, suppose you encounter this in a code base:

auto result = findRecord( /* arguments */ );
if (result == 0) {
....
}

If you don’t happen to know (or can’t easily find out) what findRecord returns, it may not be clear whether result is a pointer type or an integral type. After all, 0 (what result is tested against) could go either way. If you see the following, on the other hand,

auto result = findRecord( /* arguments */ );
if (result == nullptr) {
...
}

there’s no ambiguity: result must be a pointer type.

Advantage 3

#include<iostream>
#include <memory>
#include <thread>
#include <mutex>
using namespace std;
int f1(std::shared_ptr<int> spw) // call these only when
{
  //do something
  return 0;
}
double f2(std::unique_ptr<int> upw) // the appropriate
{
  //do something
  return 0.0;
}
bool f3(int* pw) // mutex is locked
{

return 0;
}

std::mutex f1m, f2m, f3m; // mutexes for f1, f2, and f3
using MuxtexGuard = std::lock_guard<std::mutex>;

void lockAndCallF1()
{
        MuxtexGuard g(f1m); // lock mutex for f1
        auto result = f1(static_cast<int>(0)); // pass 0 as null ptr to f1
        cout<< result<<endl;
}

void lockAndCallF2()
{
        MuxtexGuard g(f2m); // lock mutex for f2
        auto result = f2(static_cast<int>(NULL)); // pass NULL as null ptr to f2
        cout<< result<<endl;
}
void lockAndCallF3()
{
        MuxtexGuard g(f3m); // lock mutex for f2
        auto result = f3(nullptr);// pass nullptr as null ptr to f3 
        cout<< result<<endl;
} // unlock mutex
int main()
{
        lockAndCallF1();
        lockAndCallF2();
        lockAndCallF3();
        return 0;
}

Above program compile and executed successfully but lockAndCallF1, lockAndCallF2 & lockAndCallF3 have redundant code. It is pity to write code like this if we can write template for all these lockAndCallF1, lockAndCallF2 & lockAndCallF3. So it can be generalized with template. I have written template function lockAndCall instead of multiple definition lockAndCallF1, lockAndCallF2 & lockAndCallF3 for redundant code.

Code is re-factored as below:

#include<iostream>
#include <memory>
#include <thread>
#include <mutex>
using namespace std;
int f1(std::shared_ptr<int> spw) // call these only when
{
  //do something
  return 0;
}
double f2(std::unique_ptr<int> upw) // the appropriate
{
  //do something
  return 0.0;
}
bool f3(int* pw) // mutex is locked
{

return 0;
}

std::mutex f1m, f2m, f3m; // mutexes for f1, f2, and f3
using MuxtexGuard = std::lock_guard<std::mutex>;

template<typename FuncType, typename MuxType, typename PtrType>
auto lockAndCall(FuncType func, MuxType& mutex, PtrType ptr) -> decltype(func(ptr))
//decltype(auto) lockAndCall(FuncType func, MuxType& mutex, PtrType ptr)
{
        MuxtexGuard g(mutex);
        return func(ptr);
}
int main()
{
        auto result1 = lockAndCall(f1, f1m, 0); //compilation failed 
        //do something
        auto result2 = lockAndCall(f2, f2m, NULL); //compilation failed
        //do something
        auto result3 = lockAndCall(f3, f3m, nullptr);
        //do something
        return 0;
}

Detail analysis why compilation failed for lockAndCall(f1, f1m, 0) & lockAndCall(f3, f3m, nullptr) not for lockAndCall(f3, f3m, nullptr)

Why compilation of lockAndCall(f1, f1m, 0) & lockAndCall(f3, f3m, nullptr) failed?

The problem is that when 0 is passed to lockAndCall, template type deduction kicks in to figure out its type. The type of 0 is int, so that’s the type of the parameter ptr inside the instantiation of this call to lockAndCall. Unfortunately, this means that in the call to func inside lockAndCall, an int is being passed, and that’s not compatible with the std::shared_ptr<int> parameter that f1 expects. The 0 passed in the call to lockAndCall was intended to represent a null pointer, but what actually got passed was int. Trying to pass this int to f1 as a std::shared_ptr<int> is a type error. The call to lockAndCall with 0 fails because inside the template, an int is being passed to a function that requires a std::shared_ptr<int>.

The analysis for the call involving NULL is essentially the same. When NULL is passed to lockAndCall, an integral type is deduced for the parameter ptr, and a type error occurs when ptr—an int or int-like type—is passed to f2, which expects to get a std::unique_ptr<int>.

In contrast, the call involving nullptr has no trouble. When nullptr is passed to lockAndCall, the type for ptr is deduced to be std::nullptr_t. When ptr is passed to f3, there’s an implicit conversion from std::nullptr_t to int*, because std::nullptr_t implicitly converts to all pointer types.

It is recommended, Whenever you want to refer to a null pointer, use nullptr, not 0 or NULL.




回答5:


There is no direct advantage of having nullptr in the way you have shown the examples.
But consider a situation where you have 2 functions with same name; 1 takes int and another an int*

void foo(int);
void foo(int*);

If you want to call foo(int*) by passing a NULL, then the way is:

foo((int*)0); // note: foo(NULL) means foo(0)

nullptr makes it more easy and intuitive:

foo(nullptr);

Additional link from Bjarne's webpage.
Irrelevant but on C++11 side note:

auto p = 0; // makes auto as int
auto p = nullptr; // makes auto as decltype(nullptr)



回答6:


Just as others have already said, its primary advantage lies in overloads. And while explicit int vs. pointer overloads can be rare, consider standard library functions like std::fill (which has bitten me more than once in C++03):

MyClass *arr[4];
std::fill_n(arr, 4, NULL);

Doesn't compile: Cannot convert int to MyClass*.




回答7:


IMO more important than those overload issues: in deeply nested template constructs, it's hard not to lose track of the types, and giving explicit signatures is quite an endeavour. So for everything that you use, the more precisely focused to the intended purpose, the better, it will reduce the need for explicit signatures and allows the compiler to produce more insightful error messages when something goes wrong.



来源:https://stackoverflow.com/questions/13816385/what-are-the-advantages-of-using-nullptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!